<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Whisper of the Heartman]]></title><description><![CDATA[Thoughts, tips, and tricks on software development, text editors, and the industry. Expect posts on keyboard layouts, functional programming, type systems, Emacs, Nix(OS), git, Rust, and more.]]></description><link>https://blog.thomasheartman.com</link><generator>GatsbyJS</generator><lastBuildDate>Tue, 04 Oct 2022 19:26:50 GMT</lastBuildDate><atom:link href="https://blog.thomasheartman.com/rss.xml" rel="self" type="application/rss+xml"/><item><title><![CDATA[Bevy: getting started on NixOS]]></title><description><![CDATA[When trying to follow the Bevy getting started guide, I ran into some NixOS related issues. Here's what they were and what I had to do to fix them!]]></description><link>https://blog.thomasheartman.com/posts/bevy-getting-started-on-nixos</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/bevy-getting-started-on-nixos</guid><pubDate>Sat, 28 Aug 2021 15:31:35 GMT</pubDate><content:encoded>&lt;p&gt;A little while ago, I received the good news that I had gotten two (&lt;i&gt;TWO&lt;/i&gt; 🎉) of my talk proposals accepted by &lt;a href=&quot;https://ndcoslo.com/&quot;&gt;NDC Oslo&lt;/a&gt; this year: one on profiling performance issues and one on building Rust games for the browser 🥳 While this &lt;i&gt;is&lt;/i&gt; great, it also means that I need to start doing some serious work, because &lt;i&gt;these talks don&apos;t exist yet&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;For the talk on building games with Rust, I knew immediately that I wanted to use &lt;a href=&quot;https://bevyengine.org/&quot;&gt;the Bevy game engine&lt;/a&gt;. However, I&apos;ve never used Bevy before, so I thought I&apos;d start with &lt;a href=&quot;https://bevyengine.org/learn/book/introduction/&quot;&gt;the Bevy Book&lt;/a&gt; and [[https://bevyengine.org/learn/book/getting-started/][its /Getting Started/ section]]. For most cases, the docs should be sufficient, but if you run NixOS (I do 🙋), then you might run into some cases not covered by the guide. This post details all the extra steps I had to take to get through the tutorial. At the end, I&apos;ll put the whole &lt;code&gt;shell.nix&lt;/code&gt; file that I ended up with as well as any other changes I had to make.&lt;/p&gt;&lt;p&gt;This was for Bevy 0.5 running on NixOS 21.05 on a Dell XPS 9570 using the NVIDIA graphics card. If your system is different, the steps in this post may or may not work for you. But if you try and follow the steps in this post, &lt;i&gt;do&lt;/i&gt; let me know how it went &lt;a href=&quot;https://twitter.com/thomasheartman&quot;&gt;(@ me on Twitter!&lt;/a&gt;)!&lt;/p&gt;&lt;p&gt;Oh, and before we get started: I&apos;d like to extend a big thank you to everyone who helped me out in the &lt;a href=&quot;https://discord.gg/bevy&quot;&gt;Bevy discord&lt;/a&gt; as well as to the people behind the engine itself and the docs ❤️&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Initial setup&lt;/h2&gt;&lt;p&gt;Let&apos;s get a dev environment going with the dependencies we need. The Bevy GitHub repo has a [[https://github.com/bevyengine/bevy/blob/main/docs/linux_dependencies.md#nixos][linux setup file (with a specific section for NixOS!)]] that tells you what you need. As mentioned in the text, add this to a &lt;code&gt;build.rs&lt;/code&gt; file (in your project root):&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;cfg!&lt;/span&gt;(target_os = &lt;span class=&quot;hljs-string&quot;&gt;&quot;linux&quot;&lt;/span&gt;) {
        &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;cargo:rustc-link-lib=vulkan&quot;&lt;/span&gt;);
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;It also gives you a Nix shell that you can use. It contains most dependencies, but as we&apos;ll see, we need to modify it slightly (or at least I had to). The version that&apos;s there is:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-nix&quot;&gt;{ pkgs ? &lt;span class=&quot;hljs-built_in&quot;&gt;import&lt;/span&gt; &amp;#x3C;nixpkgs&gt; { } }:
&lt;span class=&quot;hljs-keyword&quot;&gt;with&lt;/span&gt; pkgs;
mkShell {
  &lt;span class=&quot;hljs-attr&quot;&gt;buildInputs&lt;/span&gt; = [
    cargo
    pkgconfig udev alsaLib lutris
    x11 xorg.libXcursor xorg.libXrandr xorg.libXi
    vulkan-tools vulkan-headers vulkan-loader vulkan-validation-layers
  ];
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Problem 1: fast compilation&lt;/h2&gt;&lt;p&gt;The first issues I ran into were in &lt;a href=&quot;https://bevyengine.org/learn/book/getting-started/setup/&quot;&gt;the /Setup/ section of the guide&lt;/a&gt;. Specifically around &lt;i&gt;fast compilation&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;The guide says to copy &lt;a href=&quot;https://github.com/bevyengine/bevy/blob/main/.cargo/config_fast_builds&quot;&gt;this Cargo config file&lt;/a&gt; into &lt;code&gt;YOUR_WORKSPACE/.cargo/config.toml&lt;/code&gt;. This config file enables fast compilation by configuring the linker and specific Rust flags. The configuration for building on Linux looks like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-toml&quot;&gt;&lt;span class=&quot;hljs-section&quot;&gt;[target.x86_64-unknown-linux-gnu]&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;linker&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;/usr/bin/clang&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;rustflags&lt;/span&gt; = [&lt;span class=&quot;hljs-string&quot;&gt;&quot;-Clink-arg=-fuse-ld=lld&quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&quot;-Zshare-generics=y&quot;&lt;/span&gt;]&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If you&apos;ve used NixOS for a bit, you&apos;ll probably realize why this won&apos;t work: there&apos;s no &lt;code&gt;/usr/bin&lt;/code&gt; directory on NixOS. Also, if you look at the &lt;code&gt;shell.nix&lt;/code&gt; file from before, there&apos;s no &lt;code&gt;clang&lt;/code&gt; &lt;i&gt;or&lt;/i&gt; &lt;code&gt;lld&lt;/code&gt; included.&lt;/p&gt;&lt;p&gt;We&apos;ll fix this by changing the linker to just &lt;code&gt;clang&lt;/code&gt; and by adding &lt;code&gt;clang&lt;/code&gt; and &lt;code&gt;lld&lt;/code&gt; to the &lt;code&gt;shell.nix&lt;/code&gt; build inputs. That means the &lt;code&gt;.cargo/config.toml&lt;/code&gt; file should look like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-toml&quot;&gt;&lt;span class=&quot;hljs-section&quot;&gt;[target.x86_64-unknown-linux-gnu]&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;linker&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;clang&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;rustflags&lt;/span&gt; = [&lt;span class=&quot;hljs-string&quot;&gt;&quot;-Clink-arg=-fuse-ld=lld&quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&quot;-Zshare-generics=y&quot;&lt;/span&gt;]&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Problem 2: Apps&lt;/h2&gt;&lt;p&gt;The next issue I ran into was in &lt;a href=&quot;https://bevyengine.org/learn/book/getting-started/apps/&quot;&gt;the next section, /Apps/.&lt;/a&gt; The basic &quot;Hello World&quot; program you get when starting a new project via Cargo built and ran just fine. However, it suddenly stopped working when I tried to import and use Bevy.&lt;/p&gt;&lt;p&gt;The error I got was:&lt;/p&gt;&lt;pre class=&quot;example&quot;&gt;target/debug/&amp;#x3C;project&gt;: error while loading shared libraries:
libudev.so.1: cannot open shared object file: No such file or
directory&lt;/pre&gt;&lt;p&gt;The solution was to modify the environment&apos;s &lt;code&gt;LD_LIBRARY_PATH&lt;/code&gt; by adding &lt;code&gt;udev&lt;/code&gt;. This took some searching to find out, but thanks to &lt;a href=&quot;https://github.com/MaikKlein/ash/issues/312#issuecomment-814491730&quot;&gt;this GitHub comment&lt;/a&gt; and @LegendOfMiracles [[https://discordapp.com/channels/691052431525675048/742884593551802431/843481717318484018][post in the Bevy Discord&apos;s #help channel]], I got there in the end.&lt;/p&gt;&lt;p&gt;In addition to &lt;code&gt;udev&lt;/code&gt; we also need to add &lt;code&gt;alsaLib&lt;/code&gt; to the &lt;code&gt;LD_LIBRARY_PATH&lt;/code&gt;. To achieve this, add this to your &lt;code&gt;shell.nix&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-nix&quot;&gt;&lt;span class=&quot;hljs-attr&quot;&gt;shellHook&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&apos;&apos;export LD_LIBRARY_PATH=&quot;$LD_LIBRARY_PATH:&lt;span class=&quot;hljs-subst&quot;&gt;${pkgs.lib.makeLibraryPath [
  pkgs.alsaLib
  pkgs.udev
]}&lt;/span&gt;&quot;&apos;&apos;&lt;/span&gt;;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Problem 3: Plugins&lt;/h2&gt;&lt;p&gt;The third and final problem I ran into was with [[https://bevyengine.org/learn/book/getting-started/plugins/][the section on /Plugins/]]. When I added &lt;code&gt;DefaultPlugins&lt;/code&gt;, the program immediately panicked with this message:&lt;/p&gt;&lt;pre class=&quot;example&quot;&gt;Finished dev [unoptimized + debuginfo] target(s) in 0.08s
 Running `target/debug/bevy-tutorial`
thread &apos;main&apos; panicked at &apos;Unable to find a GPU! Make sure you have installed required drivers!&apos;, /home/thomas/.cargo/registry/src/github.com-1ecc6299db9ec823/bevy_wgpu-0.5.0/src/wgpu_renderer.rs:47:14
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace&lt;/pre&gt;&lt;p&gt;Turns out the solution to this was to modify the &lt;code&gt;LD_LIBRARY_PATH&lt;/code&gt; further and add &lt;code&gt;vulkan-loader&lt;/code&gt; too. When I added the &lt;code&gt;vulkan-loader&lt;/code&gt; everything ran and worked as expected.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Summary and full files&lt;/h2&gt;&lt;p&gt;It took some extra work, but I got there in the end. Below are the files that I ended up with. In addition to these, remember to also add the &lt;code&gt;build.rs&lt;/code&gt; file as specified above.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;&lt;code&gt;shell.nix&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;Here&apos;s what I use for the dev environment. I use &lt;a href=&quot;https://github.com/nix-community/fenix&quot;&gt;fenix&lt;/a&gt; for managing the Rust toolchain. I&apos;ve also added &lt;code&gt;cargo-edit&lt;/code&gt; and &lt;code&gt;cargo-watch&lt;/code&gt; because they&apos;re handy tools to have. Everything else is Bevy-related.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-nix&quot;&gt;{ pkgs ? &lt;span class=&quot;hljs-built_in&quot;&gt;import&lt;/span&gt; &amp;#x3C;nixpkgs&gt; {} }:

&lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt;

  &lt;span class=&quot;hljs-attr&quot;&gt;fenix&lt;/span&gt; = &lt;span class=&quot;hljs-built_in&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&quot;&lt;span class=&quot;hljs-subst&quot;&gt;${
  fetchTarball &lt;span class=&quot;hljs-string&quot;&gt;&quot;https://github.com/nix-community/fenix/archive/main.tar.gz&quot;&lt;/span&gt;
  }&lt;/span&gt;/packages.nix&quot;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt;

pkgs.mkShell {
  &lt;span class=&quot;hljs-attr&quot;&gt;shellHook&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&apos;&apos;export LD_LIBRARY_PATH=&quot;$LD_LIBRARY_PATH:&lt;span class=&quot;hljs-subst&quot;&gt;${pkgs.lib.makeLibraryPath [
    pkgs.alsaLib
    pkgs.udev
    pkgs.vulkan-loader
  ]}&lt;/span&gt;&quot;&apos;&apos;&lt;/span&gt;;

  &lt;span class=&quot;hljs-attr&quot;&gt;buildInputs&lt;/span&gt; = &lt;span class=&quot;hljs-keyword&quot;&gt;with&lt;/span&gt; pkgs; [
    (
      &lt;span class=&quot;hljs-keyword&quot;&gt;with&lt;/span&gt; fenix;
      combine (
        &lt;span class=&quot;hljs-keyword&quot;&gt;with&lt;/span&gt; default; [
          cargo
          clippy-preview
          latest.rust-src
          rust-analyzer
          rust-std
          rustc
          rustfmt-preview
        ]
      )
    )
    cargo-edit
    cargo-watch

    lld
    clang

    &lt;span class=&quot;hljs-comment&quot;&gt;# # bevy-specific deps (from https://github.com/bevyengine/bevy/blob/main/docs/linux_dependencies.md)&lt;/span&gt;
    pkgconfig
    udev
    alsaLib
    lutris
    x11
    xorg.libXcursor
    xorg.libXrandr
    xorg.libXi
    vulkan-tools
    vulkan-headers
    vulkan-loader
    vulkan-validation-layers
  ];

}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;&lt;code&gt;.cargo/config.toml&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;This is what the full &lt;code&gt;config.toml&lt;/code&gt; file looks like after adjusting the Linux config for NixOS.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-toml&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# Add the contents of this file to `config.toml` to enable &quot;fast build&quot; configuration. Please read the notes below.&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;# &lt;span class=&quot;hljs-doctag&quot;&gt;NOTE:&lt;/span&gt; For maximum performance, build using a nightly compiler&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# If you are using rust stable, remove the &quot;-Zshare-generics=y&quot; below.&lt;/span&gt;

&lt;span class=&quot;hljs-section&quot;&gt;[target.x86_64-unknown-linux-gnu]&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;linker&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;clang&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;rustflags&lt;/span&gt; = [&lt;span class=&quot;hljs-string&quot;&gt;&quot;-Clink-arg=-fuse-ld=lld&quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&quot;-Zshare-generics=y&quot;&lt;/span&gt;]

&lt;span class=&quot;hljs-comment&quot;&gt;# &lt;span class=&quot;hljs-doctag&quot;&gt;NOTE:&lt;/span&gt; you must manually install https://github.com/michaeleisel/zld on mac. you can easily do this with the &quot;brew&quot; package manager:&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# `brew install michaeleisel/zld/zld`&lt;/span&gt;
&lt;span class=&quot;hljs-section&quot;&gt;[target.x86_64-apple-darwin]&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;rustflags&lt;/span&gt; = [&lt;span class=&quot;hljs-string&quot;&gt;&quot;-C&quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&quot;link-arg=-fuse-ld=/usr/local/bin/zld&quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&quot;-Zshare-generics=y&quot;&lt;/span&gt;]

&lt;span class=&quot;hljs-section&quot;&gt;[target.x86_64-pc-windows-msvc]&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;linker&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;rust-lld.exe&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;rustflags&lt;/span&gt; = [&lt;span class=&quot;hljs-string&quot;&gt;&quot;-Zshare-generics=y&quot;&lt;/span&gt;]

&lt;span class=&quot;hljs-comment&quot;&gt;# Optional: Uncommenting the following improves compile times, but reduces the amount of debug info to &apos;line number tables only&apos;&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# In most cases the gains are negligible, but if you are on macos and have slow compile times you should see significant gains.&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;#[profile.dev]&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;#debug = 1&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;hr&gt;&lt;p&gt;That&apos;s it for now. I hope this is useful to someone.&lt;/p&gt;&lt;p&gt;Until next time! 👋&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[2020 wrap-up]]></title><description><![CDATA[In which I go back and look at the goals I set for myself in 2020 and assess whether I achieved them or not (spoiler: mostly didn't). I also outline my (lack of) plans for 2021.]]></description><link>https://blog.thomasheartman.com/posts/2020-wrap-up</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/2020-wrap-up</guid><pubDate>Sat, 09 Jan 2021 17:17:23 GMT</pubDate><content:encoded>&lt;p&gt;At the tail end of 2019, I &lt;a href=&quot;https://blog.thomasheartman.com/posts/goodbye-2019-hello-2020&quot;&gt;published a post&lt;/a&gt; where I summarized what I&apos;d done in 2019 and laid plans for 2020, including a list of goals. Now that 2020 is (finally) over, I thought it&apos;d be a good time to review the year based on those goals.&lt;/p&gt;&lt;p&gt;I think that for the most of us, 2020 really didn&apos;t pan out the way we&apos;d planned. It certainly didn&apos;t for me. But despite the (still) raging pandemic and all the other stuff that the world threw at us, I&apos;m quite content with the year. It turned out very different to what I had imagined, but that&apos;s not necessarily a bad thing.&lt;/p&gt;&lt;p&gt;In particular, I have gained some very close friends this year, and my social life has, contrary to what you might expect, gotten &lt;i&gt;much&lt;/i&gt; better. A better and more active social life means less time spent alone in front of a computer and thus less time for working on the goals I set out for the year.&lt;/p&gt;&lt;p&gt;I also started &lt;a href=&quot;https://blog.logrocket.com/author/thomasheartman/&quot;&gt;writing articles for LogRocket&lt;/a&gt;, which I consider a significant step forward. However, being paid to write elsewhere naturally means that I spend less time writing for my own blog, for better or worse.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;2020: Review&lt;/h2&gt;&lt;p&gt;I set myself a number of so-called &lt;i&gt;SMART&lt;/i&gt; (Specific, Measurable, Achievable, Relevant, Time-bound) goals last year. Some I achieved, some I made fair progress on, and others I failed completely. Let&apos;s have a look!&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Programming language theory&lt;/h3&gt;&lt;p&gt;&lt;strong&gt;Goal&lt;/strong&gt;: Read Pierce&apos;s &lt;i&gt;Types and Programming Languages&lt;/i&gt; by July.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Status&lt;/strong&gt;: Failed.&lt;/p&gt;&lt;p&gt;I&apos;d almost forgotten about this one, but not for lack of interest. I started working on the book around March or so, but found that I was missing some basic mathematical background. So I followed the book&apos;s advice and picked up a number of other books to make sure I knew what was going on: Halmos&apos; &lt;i&gt;Naive Set Theory&lt;/i&gt;, Winskel&apos;s /The Formal Semantics of Programming Languages/, and Davey &amp;#x26; Priestley&apos;s &lt;i&gt;Introduction to Lattices and Order&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;I made it through &lt;i&gt;Naive Set Theory&lt;/i&gt; before embarking on &lt;i&gt;Introduction to Lattices and Order&lt;/i&gt;, which I have not yet finished. It seems this could take a while longer than I had anticipated.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Community engagement&lt;/h3&gt;&lt;p&gt;&lt;strong&gt;Goal&lt;/strong&gt;: Give at least three talks/workshops at community events and apply to speak at at least three conferences by the end of the year.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Status&lt;/strong&gt;: Failed ... but wait!&lt;/p&gt;&lt;p&gt;This is the goal that was impacted the most by the pandemic this year. It started well, but the cancellation of most in-person meetups got in the way of presenting at local events. I also only applied to two conferences this year, but one of those went through, and I spoke at NDC Oslo this summer about contributing to Open Source.&lt;/p&gt;&lt;p&gt;So while the exact targets specified in the goal weren&apos;t met, I&apos;d say the impact of getting that first conference talk is big enough for me to think that maybe the minutiae don&apos;t matter that much, and that the essence of the goal was achieved.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Emacs&lt;/h3&gt;&lt;p&gt;&lt;strong&gt;Goal&lt;/strong&gt;: Read the Emacs manual by February 1^st.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Status&lt;/strong&gt;: Achieved.&lt;/p&gt;&lt;p&gt;At least the year started off well! While the manual was much longer than I thought, I did get through it by the deadline ([[https://blog.thomasheartman.com/posts/tips-and-tricks-for-the-fledgling-emacs-user][and wrote about it shortly thereafter]]), so this is an easy pass. I also &lt;a href=&quot;https://blog.thomasheartman.com/posts/org-mode-tasty-tricks&quot;&gt;read the org mode manual&lt;/a&gt; a bit later and picked up some more tips and tricks.&lt;/p&gt;&lt;p&gt;As a corollary to the goal, I mentioned that I &lt;i&gt;might&lt;/i&gt; try and configure Emacs from the ground up (instead of basing it on Spacemacs), but that that wasn&apos;t a necessity. I&apos;m happy to report that I &lt;i&gt;did&lt;/i&gt; do just that around August or so. As part of configuring Emacs from the ground up, I also decided I&apos;d try and go without Vim key bindings. That went well for about six months until I accidentally (&lt;i&gt;not really&lt;/i&gt;) configured Evil again just a few days ago. &lt;i&gt;Whoops!&lt;/i&gt;&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Nix&lt;/h3&gt;&lt;p&gt;&lt;strong&gt;Goal&lt;/strong&gt;: Write about &lt;code&gt;build.nix&lt;/code&gt;, &lt;code&gt;default.nix&lt;/code&gt;, and &lt;code&gt;shell.nix&lt;/code&gt; by the end of the year.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Status&lt;/strong&gt;: Failed. Thoroughly.&lt;/p&gt;&lt;p&gt;I&apos;m not entirely sure why I didn&apos;t get around to this. I think I was planning on doing this later in the year, at which point the pandemic was very much happening and I was busy doing other things that felt more important at the time.&lt;/p&gt;&lt;p&gt;I&apos;d still like to sit down and do this at some point, but I don&apos;t know when just yet.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;OpenShift&lt;/h3&gt;&lt;p&gt;&lt;strong&gt;Goal&lt;/strong&gt;: Pass the [[https://www.redhat.com/en/services/training/ex288-red-hat-certified-specialist-openshift-application-development-exam][Red Hat Certified Specialist in OpenShift Application Development exam]] by the end of the year.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Status&lt;/strong&gt;: Failed.&lt;/p&gt;&lt;p&gt;This is another goal that almost fell off my radar. Because I was doing this in relation to work and work got rather busy for a while, I never quite got around to working on this. Until September/October, when I spent a lot of time reading up on this and preparing.&lt;/p&gt;&lt;p&gt;I took the exam again on January 6^th (already too late for the goal, but close enough; I &lt;i&gt;scheduled&lt;/i&gt; it within the deadline) and failed. Again. With the &lt;i&gt;exact same&lt;/i&gt; score as last time. And while I did clear all the stuff that I didn&apos;t previously, I scored 0% on some of the stuff that I know really well. I blame running out of time and not reading the problem text properly.&lt;/p&gt;&lt;p&gt;Oh, well. At least I learned a lot, right?&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Containers/infrastructure/Haskell/Nix&lt;/h3&gt;&lt;p&gt;&lt;strong&gt;Goal&lt;/strong&gt;: Manage a Kubernetes cluster by April 1^st, run a Haskell API (built with Nix) on it by June 1^st.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Status&lt;/strong&gt;: Failed.&lt;/p&gt;&lt;p&gt;I made some progress on this and did have the Kubernetes cluster up and running (on &lt;a href=&quot;https://www.digitalocean.com/&quot;&gt;DigitalOcean&lt;/a&gt;) in time for the first deadline. But then I just never got around to creating or setting up the Haskell API.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;2021: New goals?&lt;/h2&gt;&lt;p&gt;So what about 2021? Do I want to set any new goals? Much like [[https://daverupert.com/2020/12/twenty-twenty/][Dave Rupert]], I think I&apos;ll ease up on setting myself any goals for 2021. The pandemic is still very much present and will likely shape much of the coming year, even with vaccinations being rolled out at the moment. Based on the occurrences of the past week (/looking at you, America!/), I&apos;m also not sure whether this year is going to be any easier than the last one in other regards. So for now, I think I&apos;ll just roll with the punches and take things one at a time. I&apos;m working on a couple things, but I&apos;ll save those for later.&lt;/p&gt;&lt;p&gt;So a bit late, but happy new year to all of you! You survived! Now let&apos;s make the most of it.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Rust 2021]]></title><description><![CDATA[In which I talk about what features I want to see on the Rust roadmap in 2021. Const generics and generic associated types get honorable mentions, but my vote goes to nested OR-patterns and trait aliases.]]></description><link>https://blog.thomasheartman.com/posts/rust-2021</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/rust-2021</guid><pubDate>Sun, 27 Sep 2020 20:05:45 GMT</pubDate><content:encoded>&lt;p&gt;This is my response to the Rust Core Team&apos;s &lt;a href=&quot;https://blog.rust-lang.org/2020/09/03/Planning-2021-Roadmap.html&quot;&gt;2021 Roadmap call for blogs&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;A year ago, &lt;a href=&quot;https://blog.thomasheartman.com/posts/rust-2020&quot;&gt;stabilizing slice patterns was at the top of my wish list for Rust 2020&lt;/a&gt;. I&apos;d been waiting for that for a long time. A few months later, it landed on the stable channel with release 1.42. I don&apos;t expect to be quite as lucky time around, but one can dream.&lt;/p&gt;&lt;p&gt;At the outset, I didn&apos;t really have any strong wishes for the next year. But when I sat down and thought about it, I came up with two things that I&apos;ve run into lately that I know are being worked on and that I would love to see finalized.&lt;/p&gt;&lt;p&gt;Besides these two, there&apos;s &lt;a href=&quot;https://github.com/rust-lang/rust/issues/44580&quot;&gt;const generics&lt;/a&gt; and &lt;a href=&quot;https://github.com/rust-lang/rust/issues/44265&quot;&gt;GATs&lt;/a&gt;. High-profile features that get a lot of love in the community. The thing about these two, however, is that whenever I read up on them, they seem great and super useful, but I don&apos;t think I&apos;ve actually run into any cases where I need them while programming. So while I hope the work on these continues, I want to turn my attention to two other points: nested OR-patterns and trait aliases.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Nested OR-patterns&lt;/h2&gt;&lt;p&gt;This was mentioned as an upcoming feature in the post &lt;a href=&quot;https://blog.rust-lang.org/inside-rust/2020/03/04/recent-future-pattern-matching-improvements.html#nested-or-patterns&quot;&gt;Recent and future pattern matching improvements&lt;/a&gt; from the &lt;i&gt;Inside Rust Blog&lt;/i&gt; in March. In short, it allows you to nest patterns when pattern matching.&lt;/p&gt;&lt;p&gt;Imagine you have an &lt;code&gt;Option&amp;#x3C;u8&gt;&lt;/code&gt; and you want to check whether the possibly contained &lt;code&gt;u8&lt;/code&gt; is &lt;code&gt;4&lt;/code&gt; or &lt;code&gt;13&lt;/code&gt;. Without using the &lt;code&gt;or_patterns&lt;/code&gt;, you&apos;d have to do something like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;is_unlucky&lt;/span&gt;&lt;/span&gt;(n: &lt;span class=&quot;hljs-built_in&quot;&gt;Option&lt;/span&gt;&amp;#x3C;&lt;span class=&quot;hljs-built_in&quot;&gt;u8&lt;/span&gt;&gt;) -&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;bool&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; n {
        &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;) =&gt; &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;,
        &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;13&lt;/span&gt;) =&gt; &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;,
        _ =&gt; &lt;span class=&quot;hljs-literal&quot;&gt;false&lt;/span&gt;,
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Notice that double &lt;code&gt;Some&lt;/code&gt; check? Using the &lt;code&gt;or_patterns&lt;/code&gt; feature, we can simplify this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// make sure you&apos;re on nightly!&lt;/span&gt;
&lt;span class=&quot;hljs-meta&quot;&gt;#![feature(or_patterns)]&lt;/span&gt;

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;is_unlucky&lt;/span&gt;&lt;/span&gt;(n: &lt;span class=&quot;hljs-built_in&quot;&gt;Option&lt;/span&gt;&amp;#x3C;&lt;span class=&quot;hljs-built_in&quot;&gt;u8&lt;/span&gt;&gt;) -&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;bool&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; n {
        &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt; | &lt;span class=&quot;hljs-number&quot;&gt;13&lt;/span&gt;) =&gt; &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;,
        _ =&gt; &lt;span class=&quot;hljs-literal&quot;&gt;false&lt;/span&gt;,
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As always, this is a simplified and contrived example, but it can simplify code considerably in some cases. And yes, I&apos;m sure it can make some code even harder to read too, but that&apos;s a tradeoff I&apos;m willing to make.&lt;/p&gt;&lt;p&gt;So where are we on this? There is an &lt;a href=&quot;https://github.com/rust-lang/rust/issues/54883&quot;&gt;open tracking issue&lt;/a&gt; for it. But there seems to be some blocking issues at the moment, including &lt;a href=&quot;https://github.com/rust-lang/rust/issues/72680&quot;&gt;one that makes the compiler panic&lt;/a&gt;, so I&apos;m not sure what the status is. There hasn&apos;t been any activity on this since July, but I&apos;m hopeful that we might see some progress on this in the coming year.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Trait aliases&lt;/h2&gt;&lt;p&gt;Another feature that I&apos;ve wished for at times is trait aliases (thanks to or Igor Aleksanov (&lt;a href=&quot;https://github.com/popzxc&quot;&gt;popzxc&lt;/a&gt;) for &lt;a href=&quot;https://popzxc.github.io/rust-2021&quot;&gt;mentioning this in their Rust 2021 post&lt;/a&gt;). This feature would allow you to refer to a collection of traits with an alias that you choose.&lt;/p&gt;&lt;p&gt;This is particularly nifty in situations where you use the same set of traits to define trait bounds over a number of functions. Instead of specifying the same combination over and over again, you can give the combination a name and use that name from there on.&lt;/p&gt;&lt;p&gt;Using Aleksanov&apos;s post as inspiration again, we could have something like this (without trait aliases):&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;MyTrait&lt;/span&gt;&lt;/span&gt; {}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T&gt;(x: &amp;#x26;T)
&lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;
    T: MyTrait + &lt;span class=&quot;hljs-built_in&quot;&gt;Send&lt;/span&gt; + std::fmt::&lt;span class=&quot;hljs-built_in&quot;&gt;Debug&lt;/span&gt;,
{
    &lt;span class=&quot;hljs-comment&quot;&gt;// do something with x here&lt;/span&gt;
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;g&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T&gt;(x: &amp;#x26;T)
&lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;
    T: MyTrait + &lt;span class=&quot;hljs-built_in&quot;&gt;Send&lt;/span&gt; + std::fmt::&lt;span class=&quot;hljs-built_in&quot;&gt;Debug&lt;/span&gt;,
{
    &lt;span class=&quot;hljs-comment&quot;&gt;// do something else with x here&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;There are a few things about this code that could be improved with trait aliases. Most notably is the fact that the combination of the three traits we&apos;re using (&lt;code&gt;MyTrait&lt;/code&gt;, &lt;code&gt;Send&lt;/code&gt;, &lt;code&gt;std::fmt::Debug&lt;/code&gt;) is repeated several times. It&apos;s not clear from the context whether these are intentionally or accidentally the same. If they are supposed to be the same, then when changing the combination one place, you&apos;d have to remember to change it everywhere else. And while it&apos;s not necessarily bad, this combination is fairly verbose.&lt;/p&gt;&lt;p&gt;By using a trait alias, we can also give this combination of traits a more meaningful and descriptive name. This can help us better communicate to other developers (and to our future selves) why this combination is what it is.&lt;/p&gt;&lt;p&gt;Using the &lt;code&gt;trait_alias&lt;/code&gt; feature on nightly, we can instead write it like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// again: you need to be on the nightly channel for this&lt;/span&gt;
&lt;span class=&quot;hljs-meta&quot;&gt;#![feature(trait_alias)]&lt;/span&gt;

&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;MyTrait&lt;/span&gt;&lt;/span&gt; {}

&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;MyExtendedTrait&lt;/span&gt;&lt;/span&gt; = MyTrait + &lt;span class=&quot;hljs-built_in&quot;&gt;Send&lt;/span&gt; + std::fmt::&lt;span class=&quot;hljs-built_in&quot;&gt;Debug&lt;/span&gt;;

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T&gt;(x: &amp;#x26;T)
&lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;
    T: MyExtendedTrait,
{
    &lt;span class=&quot;hljs-comment&quot;&gt;// do something with x here&lt;/span&gt;
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;g&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T&gt;(x: &amp;#x26;T)
&lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;
    T: MyExtendedTrait,
{
    &lt;span class=&quot;hljs-comment&quot;&gt;// do something else with x here&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;At first, it might only look like we&apos;ve added a line or two. But by grouping the trait combination under a new alias, we&apos;ve ensured that the functions will change their trait bounds in lockstep. We have also given the trait combination a more meaningful name, though, admittedly, &lt;code&gt;MyExtendedTrait&lt;/code&gt; isn&apos;t my strongest effort.&lt;/p&gt;&lt;p&gt;Much like with nested OR-patterns, there is a &lt;a href=&quot;https://github.com/rust-lang/rust/issues/41517&quot;&gt;tracking issue&lt;/a&gt; issue for this. There seems to have been some activity back in March, but not much since.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;That&apos;s it for now!&lt;/h2&gt;&lt;p&gt;It&apos;s easy to just sit back and wish for new features when you&apos;re not the one implementing them. I&apos;m very grateful to all the Rust teams for all their efforts, and I trust them wholeheartedly on what features to focus on in the coming year, whether they align with my wish list or not.&lt;/p&gt;&lt;p&gt;Rust continues to be one of the most exciting programming languages around and with one of the most welcoming communities to boot! As always: To everyone involved with the language, the ecosystem, and the community (and all the other parts that I&apos;m forgetting): thank you very much. I&apos;m looking forward to another year (and many more) with you!&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Understanding lifetimes]]></title><description><![CDATA[In which we run into Rust's lifetimes. What are they? And maybe more importantly: WHY are they? Also, how do we work with them? We'll try and get a grip of the basics in this article.]]></description><link>https://blog.thomasheartman.com/posts/understanding-lifetimes</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/understanding-lifetimes</guid><pubDate>Sun, 20 Sep 2020 09:50:42 GMT</pubDate><content:encoded>&lt;pre class=&quot;aside&quot;&gt;This article was originally published by LogRocket on their blog under
the title /Understanding lifetimes in Rust/. You can find their
version [[https://blog.logrocket.com/understanding-lifetimes-in-rust/][here]].&lt;/pre&gt;&lt;p&gt;You sit down for another crack at this Rust-thing. Last time went pretty smoothly except for some minor hiccups with the borrow checker. But you got through it and gained a slightly better understanding of how it works in the process. Maybe it&apos;s all worth it in the end?&lt;/p&gt;&lt;p&gt;Today, though, you&apos;ve got some grand plans and you&apos;re not going to let the borrow checker stop you! You can practically feel the energy coursing through your veins as you imprint your thoughts on the keyboard and translate them into pure Rust. This must be that sweet feeling you&apos;ve heard so much about. You save your project, start the compilation process, and ...&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;error[E0597]: `x` does not live long enough&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;You sigh. &lt;i&gt;Not this again.&lt;/i&gt;&lt;/p&gt;&lt;p&gt;You take a deep breath, lower your shoulders, and read the error message one more time. &apos;Does not live long enough&apos;? &lt;i&gt;What does that even mean?&lt;/i&gt;&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Introducing lifetimes&lt;/h2&gt;&lt;p&gt;You&apos;ve run into another one of Rust&apos;s peculiarities: &lt;i&gt;lifetimes&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;Lifetimes are how the Rust compiler keeps track of how long references are valid for. If you remember the &lt;a href=&quot;https://blog.logrocket.com/introducing-the-rust-borrow-checker/&quot;&gt;article on understanding the borrow checker&lt;/a&gt;, you&apos;ll know that checking references is one of the borrow checker&apos;s main responsibilities. Lifetimes help the borrow checker ensure that you never have invalid references.&lt;/p&gt;&lt;p&gt;&lt;i&gt;Lifetime annotations&lt;/i&gt;, then, let &lt;strong&gt;you&lt;/strong&gt; tell the borrow checker how long references are valid for. In many cases, the borrow checker can infer the correct lifetimes and take care of everything on its own. But often it needs your help to figure it out.&lt;/p&gt;&lt;p&gt;In this post, we&apos;ll go over the basics of lifetimes and annotations and how to work with them. We&apos;ll also look at some common scenarios you might run into and how you can solve them with lifetimes. I&apos;m expecting a basic grasp of Rust and some if its concepts (such as the borrow checker), but nothing particularly deep.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Lifetime annotations&lt;/h3&gt;&lt;p&gt;Before we go any further, just a short note on the notation of lifetimes, as it&apos;s a bit different from what you get in a lot of other languages.&lt;/p&gt;&lt;p&gt;Lifetimes are annotated by a leading apostrophe followed by a variable name. When talking about generic lifetimes, we often use single, lowercase letters, starting from ~&apos;a~, ~&apos;b~, etc. However, there is nothing stopping you from using longer, more explanatory names if that suits you better.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Why we need lifetimes&lt;/h3&gt;&lt;p&gt;If they&apos;re such a weird feature, then why do we need lifetimes? The answer, my friend, lies in Rust&apos;s ownership model. The borrow checker takes care of allocating and freeing memory and also of making sure that no references point to memory that has been freed. Like borrows, lifetimes are checked at compile-time, which means that your program can&apos;t compile if the borrow checker deems the references invalid.&lt;/p&gt;&lt;p&gt;In particular, lifetimes are important to keep in mind when returning references from functions and when creating structs with references. These are both common situations, and it&apos;s easy to get lost if you don&apos;t understand what&apos;s going on.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;The explanatory example&lt;/h3&gt;&lt;p&gt;Ultimately, lifetimes are a matter of scope. Values get dropped when they go out of scope and any references to them after they have been dropped are invalid.&lt;/p&gt;&lt;p&gt;The simplest way to demonstrate lifetimes is something like the following example, shamelessly stolen/adapted from &lt;a href=&quot;https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#the-borrow-checker&quot;&gt;the Book&apos;s chapter on lifetimes&lt;/a&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// this code sample does *not* compile&lt;/span&gt;
{
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; x;
    {                           &lt;span class=&quot;hljs-comment&quot;&gt;// create new scope&lt;/span&gt;
        &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; y = &lt;span class=&quot;hljs-number&quot;&gt;42&lt;/span&gt;;
        x = &amp;#x26;y;
    }                           &lt;span class=&quot;hljs-comment&quot;&gt;// y is dropped&lt;/span&gt;

    &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;The value of &apos;x&apos; is {}.&quot;&lt;/span&gt;, x);
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This little piece of code has two distinct scopes. When the inner scope closes, &lt;code&gt;y&lt;/code&gt; is dropped. At that point, even if &lt;code&gt;x&lt;/code&gt; is still available in the outer scope, the reference is invalid because the value it pointed to is dropped: The value that &lt;code&gt;x&lt;/code&gt; points to &apos;does not live long enough&apos;.&lt;/p&gt;&lt;p&gt;In lifetime jargon, we can say that the outer scope has the lifetime ~&apos;outer~ and the inner scope the lifetime ~&apos;inner~. ~&apos;outer~ clearly outlives ~&apos;inner~ in this case. When ~&apos;inner~ ends, all values with that lifetime are invalidated.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Lifetime elision&lt;/h3&gt;&lt;p&gt;When writing functions that accept references as arguments, the compiler can infer the correct lifetimes in many cases, saving us the trouble of writing them out by hand. When lifetime annotations are implicit, we call this &lt;i&gt;lifetime elision&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;The compiler uses three rules to figure out whether lifetime annotations can be elided or not. &lt;a href=&quot;https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-elision&quot;&gt;The section on lifetime elision&lt;/a&gt; talks about these rules in detail, but the short form is that you can elide lifetime annotations in functions if one of the following is true:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;The function doesn&apos;t return a reference.&lt;/li&gt;&lt;li&gt;There is exactly one reference input parameter.&lt;/li&gt;&lt;li&gt;The function is a method, taking &lt;code&gt;&amp;#x26;self&lt;/code&gt; or &lt;code&gt;&amp;#x26;mut self&lt;/code&gt; as the&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;first parameter.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Examples and common problems&lt;/h2&gt;&lt;p&gt;Lifetimes are a tricky thing to wrap your head around, and it&apos;s unlikely that a wall of text will make you really understand how they work. The best way to get a proper understanding is of course to play around with them yourself and solve problems, but a couple of examples can go a long way.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Returning references from functions&lt;/h3&gt;&lt;p&gt;You can&apos;t return a reference from a function without also passing in a reference. If you try, you&apos;ll find that the reference is invalid as soon as the function returns and your program won&apos;t compile&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;&lt;p&gt;If your function takes exactly one reference parameter, then you&apos;ll be fine without annotations. All output references will be given the same lifetime as the input parameter. As such, this simple function will compile just fine, even if there are no explicit lifetime annotations:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt;&lt;/span&gt;(s: &amp;#x26;&lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;) -&gt; &amp;#x26;&lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt; {
    s
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;However, if we add another input string parameter (even if we don&apos;t use it), we&apos;ll suddenly not be able to compile this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// this code sample does *not* compile&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt;&lt;/span&gt;(s: &amp;#x26;&lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;, t: &amp;#x26;&lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;) -&gt; &amp;#x26;&lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; s.len() &gt; &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; { s } &lt;span class=&quot;hljs-keyword&quot;&gt;else&lt;/span&gt; { t }
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This is because of how the automatic lifetime annotation works. When a function accepts multiple references, they&apos;re each given their own lifetime. We know that the returned reference must be one of the references we received as an input argument, but we don&apos;t know which one. What goes in place of the ~&apos;???~ below?&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// this code sample does *not* compile&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt;&lt;/span&gt;&amp;#x3C;&lt;span class=&quot;hljs-symbol&quot;&gt;&apos;a&lt;/span&gt;, &lt;span class=&quot;hljs-symbol&quot;&gt;&apos;b&lt;/span&gt;&gt;(s: &amp;#x26;&lt;span class=&quot;hljs-symbol&quot;&gt;&apos;a&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;, t: &amp;#x26;&lt;span class=&quot;hljs-symbol&quot;&gt;&apos;b&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;) -&gt; &amp;#x26;&apos;??? &lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; s.len() &gt; &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; { s } &lt;span class=&quot;hljs-keyword&quot;&gt;else&lt;/span&gt; { t }
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Imagine that we want to use the returned value outside of this function. What lifetime would we assign to it? The only thing we can guarantee is that the reference we return is valid for &lt;i&gt;at least&lt;/i&gt; as long as the &lt;i&gt;shortest-lived&lt;/i&gt; reference we pass into the function. That tells the compiler that these two references are definitely valid for the shorter lifetime. We cannot give any guarantees outside of that.&lt;/p&gt;&lt;p&gt;The way we achieve this, is by giving both input parameters the same lifetime annotation. It&apos;s how we tell the compiler that &apos;as long as both of these input parameters are valid, so is the returned value&apos;.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt;&lt;/span&gt;&amp;#x3C;&lt;span class=&quot;hljs-symbol&quot;&gt;&apos;a&lt;/span&gt;&gt;(s: &amp;#x26;&lt;span class=&quot;hljs-symbol&quot;&gt;&apos;a&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;, t: &amp;#x26;&lt;span class=&quot;hljs-symbol&quot;&gt;&apos;a&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;) -&gt; &amp;#x26;&lt;span class=&quot;hljs-symbol&quot;&gt;&apos;a&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; s.len() &gt; &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; { s } &lt;span class=&quot;hljs-keyword&quot;&gt;else&lt;/span&gt; { t }
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If you&apos;re returning a reference from a function that takes multiple input lifetime parameters, but you know exactly which one it is you&apos;re returning, you can annotate that specific lifetime. That way, the relationship between the lifetimes doesn&apos;t matter anymore.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt;&lt;/span&gt;&amp;#x3C;&lt;span class=&quot;hljs-symbol&quot;&gt;&apos;a&lt;/span&gt;, &lt;span class=&quot;hljs-symbol&quot;&gt;&apos;b&lt;/span&gt;&gt;(s: &amp;#x26;&lt;span class=&quot;hljs-symbol&quot;&gt;&apos;a&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;, _t: &amp;#x26;&lt;span class=&quot;hljs-symbol&quot;&gt;&apos;b&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;) -&gt; &amp;#x26;&lt;span class=&quot;hljs-symbol&quot;&gt;&apos;a&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt; {
    s
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Structs with references&lt;/h3&gt;&lt;p&gt;References in structs can be a real hassle. You&apos;re often better off avoiding them and using owned values instead. That way, you don&apos;t need to worry about references being invalidated and lifetimes not lasting long enough. In my experience, it&apos;s usually also what you want.&lt;/p&gt;&lt;p&gt;However, there are certain cases where structs with references are exactly what you want. In particular: if you want to create a &apos;view&apos; into something else. Using structs with references is a great way of organizing some data into a package that&apos;s easier to handle, without moving or copying data. This means that the original data source can still be referenced elsewhere and that we save on the extra work it would be to clone the data.&lt;/p&gt;&lt;p&gt;Here&apos;s an example. Imagine that we want to find the first and the last sentence of a paragraph and keep them in a struct &lt;code&gt;S&lt;/code&gt;. Because we don&apos;t want to copy the data, we need to use references and give them lifetime annotations.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;S&lt;/span&gt;&lt;/span&gt;&amp;#x3C;&lt;span class=&quot;hljs-symbol&quot;&gt;&apos;a&lt;/span&gt;&gt; {
    first: &amp;#x26;&lt;span class=&quot;hljs-symbol&quot;&gt;&apos;a&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;,
    last: &amp;#x26;&lt;span class=&quot;hljs-symbol&quot;&gt;&apos;a&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;,
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We could use a function like this to populate the struct. For simplicity&apos;s sake, we&apos;ll assume that a full stop is the only sentence-ending punctuation mark in use. If the paragraph is empty, we&apos;ll return &lt;code&gt;None&lt;/code&gt;, and if there is only a single sentence, we&apos;ll use that as both the first and the last sentence:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;try_create&lt;/span&gt;&lt;/span&gt;(paragraph: &amp;#x26;&lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;) -&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;Option&lt;/span&gt;&amp;#x3C;S&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;mut&lt;/span&gt; sentences = paragraph.split(&lt;span class=&quot;hljs-string&quot;&gt;&apos;.&apos;&lt;/span&gt;).filter(|s| !s.is_empty());
    &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; (sentences.next(), sentences.next_back()) {
        (&lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(first), &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(last)) =&gt; &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(S { first, last }),
        (&lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(first), &lt;span class=&quot;hljs-literal&quot;&gt;None&lt;/span&gt;) =&gt; &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(S { first, last: first }),
        _ =&gt; &lt;span class=&quot;hljs-literal&quot;&gt;None&lt;/span&gt;,
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Notice how we don&apos;t need to annotate lifetimes in the function signature because the compiler can figure it out for us. In a case like this, there is really only one choice: the lifetime of the input string. Pretty neat, huh?&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Summary and further reading&lt;/h2&gt;&lt;p&gt;This has been a cursory glance at lifetimes and lifetime annotations. We have glossed over a lot of the finer and more intricate details of how lifetimes work, but we&apos;ve covered enough ground that you should be able to reason about them when you run into an issue.&lt;/p&gt;&lt;p&gt;Because lifetimes are such an important part of Rust, I encourage you to have a look at the &lt;a href=&quot;https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html&quot;&gt;Validating References with Lifetimes&lt;/a&gt; chapter of &lt;a href=&quot;https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html&quot;&gt;The Book&lt;/a&gt; if you want a more comprehensive introduction.&lt;/p&gt;&lt;p&gt;Furthermore, if you feel like you&apos;ve got a decent grasp on lifetimes but want to dive a bit deeper, check out Jon Gjengset&apos;s excellent video &lt;a href=&quot;https://youtu.be/rAl-9HwD858&quot;&gt;Crust of Rust: Lifetime Annotations&lt;/a&gt;, where he explores a case that needs multiple explicit lifetime annotations. He also gives a great introduction to lifetime annotations in general, so it&apos;s well worth a watch just for that.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;/div&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;Well, you can use the ~&apos;static~ lifetime, but that&apos;s probably not what you want. It&apos;s also outside the scope of this article, so let&apos;s forget about that for now.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dl id=&quot;footnotes&quot;&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;Well, you can use the ~&apos;static~ lifetime, but that&apos;s probably not what you want. It&apos;s also outside the scope of this article, so let&apos;s forget about that for now.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;/dl&gt;</content:encoded></item><item><title><![CDATA[Meet the borrow checker]]></title><description><![CDATA[In which we encounter the Rust borrow checker for the first time and try and understand just what it is. We also look at some solutions to common problems.]]></description><link>https://blog.thomasheartman.com/posts/meet-the-borrow-checker</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/meet-the-borrow-checker</guid><pubDate>Sun, 16 Aug 2020 13:04:31 GMT</pubDate><content:encoded>&lt;pre class=&quot;aside&quot;&gt;This article was originally published by LogRocket on their blog under
the title /Understanding the Rust borrow checker/. You can find their
version [[https://blog.logrocket.com/introducing-the-rust-borrow-checker/][here]].&lt;/pre&gt;&lt;p&gt;You&apos;ve heard a lot about it, you&apos;ve bought into the hype, and the day has finally come. It&apos;s time for you to start writing Rust!&lt;/p&gt;&lt;p&gt;So you sit down---hands on the keyboard, heart giddy with anticipation---and write a few lines of code. You run the &lt;code&gt;cargo run&lt;/code&gt; command, excited to see whether the program works as expected. You&apos;ve heard Rust is one of those &apos;once it compiles, it works&apos; languages and want to test it for yourself. The compiler starts up, you follow the output, when suddenly:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;error[E0382]: borrow of moved value&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Uh-oh. Seems like you&apos;ve run into ... (&lt;strong&gt;puts on scary voice&lt;/strong&gt;) the /borrow checker/! Dun, dun, DUUUUUUN!&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The ... borrow checker?&lt;/h2&gt;&lt;p&gt;That&apos;s right. The borrow checker is an essential part of the Rust language and part of what makes Rust Rust. The borrow checker helps you (or forces you to) manage &lt;i&gt;ownership&lt;/i&gt;. As &lt;a href=&quot;https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html&quot;&gt;chapter 4 (/Understanding Ownership/)&lt;/a&gt; of [[https://doc.rust-lang.org/book/][the Rust Programming Language]] puts it: &quot;Ownership is Rust&apos;s most unique feature, and it enables Rust to make memory safety guarantees without needing a garbage collector.&quot;&lt;/p&gt;&lt;p&gt;Ownership, borrow checker, and garbage collectors: There&apos;s a lot to unpack in the above paragraph, so let&apos;s break it down a bit. We&apos;ll look at what the borrow checker does for us (and what it stops us from doing), what guarantees it gives us, and how it compares to other forms of memory management. I&apos;ll assume that you have some experience with writing code in higher level languages such as Python, JavaScript, or C#, but not necessarily that you&apos;re familiar with how computer memory works.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Garbage collection vs manual memory allocation vs the borrow checker&lt;/h3&gt;&lt;p&gt;Let&apos;s talk about memory and memory management for a minute. In most popular programming languages, you don&apos;t need to think about where your variables are stored. You simply declare them and the language runtime takes care of the rest via a garbage collector. This abstracts away how the computer memory actually works and makes it easier and more uniform to work with. This is a good thing.&lt;/p&gt;&lt;p&gt;However: we need to peel back a layer to talk about how this compares to the borrow checker. We&apos;ll start by looking at the &lt;i&gt;stack&lt;/i&gt; and the &lt;i&gt;heap&lt;/i&gt;.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h4&gt;The stack and the heap&lt;/h4&gt;&lt;p&gt;Your programs have access to two kinds of memory where it can store values: the stack and the heap. These differ in a number of ways, but for our sake, the most important difference is that data that is stored on the stack must have a known, fixed size. Data on the heap can be of any arbitrary size.&lt;/p&gt;&lt;p&gt;What do I mean by size? The size is how many bytes it takes to store the data. In broad terms, certain data types, such as booleans, characters, and integers, have a fixed size. These are easy to put on the stack. On the other hand, data types such as strings, lists, and other collections, can be of any arbitrary size. As such, they cannot be stored on the stack, and we must instead use the heap.&lt;/p&gt;&lt;p&gt;Because data of arbitrary size can be stored on the heap, the computer needs to find a chunk of memory large enough to fit whatever we are looking to store. This is time-consuming, and the program also doesn&apos;t have direct access to the data as with the stack, but is instead left with a &lt;i&gt;pointer&lt;/i&gt; to where the data is stored.&lt;/p&gt;&lt;p&gt;A pointer is pretty much what it says on the tin. It &lt;i&gt;points to&lt;/i&gt; some memory address on the heap where the data you&apos;re looking for can be found. There&apos;s any number of pointer tutorials out there on the web, and which one works for you may depend on your background. But for a quick primer, [[https://dev.to/codemouse92/comment/28fl][here&apos;s one I found that explains C pointers pretty well]] (by &lt;a href=&quot;https://dev.to/codemouse92/comment/28fl&quot;&gt;Jason C. McDonald&lt;/a&gt;).&lt;/p&gt;&lt;p&gt;What is the point of having these two different memory stores? Because of the way the stack works, data access on the stack is very fast and easy, but requires the data to conform to certain standards. The heap is slower, but more versatile, and is thus useful for when you can&apos;t use the stack.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h4&gt;Garbage collection&lt;/h4&gt;&lt;p&gt;In garbage collected languages, you don&apos;t need to worry about what goes on the stack and what goes on the heap. Data that goes on the stack gets dropped once it goes out of scope. Data that lives on the heap is taken care of by the garbage collector once it&apos;s no longer needed.&lt;/p&gt;&lt;p&gt;In languages like C, on the other hand, you need to manage memory yourself. Where you might simply initialize a list in higher level languages, you need to manually allocate memory on the heap in C. And when you&apos;ve allocated memory, you should also free the memory once you&apos;re done with it to avoid memory leaks. But take care: Memory should only be freed once.&lt;/p&gt;&lt;p&gt;This process of manual allocation and freeing is error-prone. In fact, a Microsoft representative has said that [[https://thenewstack.io/microsoft-rust-is-the-industrys-best-chance-at-safe-systems-programming/][70% of all of Microsoft&apos;s vulnerabilities and exploits are memory-related]]! So why would you use manual memory management? Because it allows for more control and can often give better performance characteristics than garbage collection. The program doesn&apos;t need to stop what it&apos;s doing and spend time finding out what it needs to clean up before cleaning it up.&lt;/p&gt;&lt;p&gt;Rust&apos;s ownership model feels like something in between. By keeping track of where data is used throughout the program and by following a set of rules, the borrow checker is able to determine where data needs to be initialized and where it needs to be freed (or &lt;i&gt;dropped&lt;/i&gt;, in Rust terms). It&apos;s like it auto-inserts memory allocations and frees for you, giving you the convenience of a garbage collector, but with the speed and efficiency of manual management.&lt;/p&gt;&lt;p&gt;The way this comes out in practice, is that when passing variables around you can do one of three things. You can &lt;i&gt;move&lt;/i&gt; the data itself and give up ownership in the process. You can create a &lt;i&gt;copy&lt;/i&gt; of the data and pass that along. Or you can pass a &lt;i&gt;reference&lt;/i&gt; to the data and retain ownership, letting the recipient borrow it for a while. Which one is more appropriate depends entirely on the situation.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Other borrow checker superpowers: paralyzed or parallelized?&lt;/h3&gt;&lt;p&gt;In addition to handling memory allocation and freeing for the programmer, the borrow checker also prevents data races (though not general race conditions) through its set of sharing rules.&lt;/p&gt;&lt;p&gt;These same borrowing rules also help you work with concurrent and parallel code without having to worry about memory safety, enabling Rust&apos;s [[https://doc.rust-lang.org/book/ch16-00-concurrency.html][fearless concurrency]].&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Drawbacks&lt;/h3&gt;&lt;p&gt;But as with all good things in life, Rust&apos;s ownership system comes with it&apos;s set of drawbacks. Indeed, without any drawbacks, this article probably wouldn&apos;t exist. The borrow checker can be tricky to understand and work with. So much so that it&apos;s pretty common for newcomers to the Rust community to get stuck &apos;fighting the borrow checker&apos; (and yes, I&apos;ve personally lost many hours of my life to that struggle).&lt;/p&gt;&lt;p&gt;For instance, sharing data can suddenly become a problem, especially if you need to mutate it at the same time. Certain data structures that are super easy to create from scratch in other languages are very hard to get right in Rust. For a good example of the latter, check out the book [[https://rust-unofficial.github.io/too-many-lists/index.html][Learn Rust With Entirely Too Many Linked Lists]]. It goes through a number of ways to implement a linked list Rust and details all the issues the author ran into on the way there. It&apos;s both informative and very entertaining, so it&apos;s well worth a look.&lt;/p&gt;&lt;p&gt;But once you get on board with the borrow checker, things start to improve. I quite like &lt;a href=&quot;https://www.reddit.com/user/dnkndnts/&quot;&gt;Reddit user dnkndnts&lt;/a&gt;&apos; explanation from &lt;a href=&quot;https://www.reddit.com/r/rust/comments/5ny09j/tips_to_not_fight_the_borrow_checker/dcf7t46/&quot;&gt;this comment&lt;/a&gt;:&lt;/p&gt;&lt;blockquote&gt;[The borrow checker] operates by a few simple rules. If you don&apos;t understand
or at least have some intuition for what those rules are, then it&apos;s going to
be about as useful as using a spell checker to help you write in a language
you don&apos;t even know: it&apos;ll just reject everything you say.

Once you know the rules the borrow checker is based on, you&apos;ll find it useful
rather than oppressive and annoying, just like a spell checker.&lt;/blockquote&gt;&lt;p&gt;And what are these rules? Here are the two most important ones to remember concerning variables that are stored on the heap:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;When passing a variable (instead of a reference to the variable) to&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;another function, you are giving up ownership. The other function is now the owner of this variable and you can&apos;t use it anymore.&lt;/p&gt;&lt;ol&gt;&lt;li&gt;When passing references to a variable (lending it out), you can have&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;&lt;strong&gt;either&lt;/strong&gt; as many immutable borrows as you want &lt;strong&gt;or&lt;/strong&gt; a single mutable borrow. Once you start borrowing mutably, &lt;i&gt;there can be only one&lt;/i&gt;.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;In practice&lt;/h2&gt;&lt;p&gt;With some understanding of what the borrow checker is and how it works, let&apos;s examine how it affects us in practice. We&apos;ll be working with the &lt;code&gt;Vec&amp;#x3C;T&gt;&lt;/code&gt; type, which is Rust&apos;s version of a growable list (analogous to Python&apos;s lists or JavaScript&apos;s arrays). Because it doesn&apos;t have a fixed size, a &lt;code&gt;Vec&lt;/code&gt; needs to be heap-allocated.&lt;/p&gt;&lt;p&gt;The example may be contrived, but it demonstrates the basic principles. We&apos;ll create a vector, call a function that simply accepts it as an argument, and then try and see what&apos;s inside later.&lt;/p&gt;&lt;p&gt;Note: this code sample &lt;strong&gt;does not compile&lt;/strong&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;hold_my_vec&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T&gt;(_: &lt;span class=&quot;hljs-built_in&quot;&gt;Vec&lt;/span&gt;&amp;#x3C;T&gt;) {}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; v = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;7&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;11&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;13&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;17&lt;/span&gt;];
    hold_my_vec(v);
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; element = v.get(&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;);

    &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;I got this element from the vector: {:?}&quot;&lt;/span&gt;, element);
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;When trying to run this, you&apos;ll get the following compiler error:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;error[E0382]: borrow of moved value: `v`
--&gt; src/main.rs:6:19
          |
        4 |     &lt;span class=&quot;hljs-built_in&quot;&gt;let&lt;/span&gt; v = vec![2, 3, 5, 7, 11, 13, 17];
          |         - move occurs because `v` has &lt;span class=&quot;hljs-built_in&quot;&gt;type&lt;/span&gt; `std::vec::Vec&amp;#x3C;i32&gt;`, &lt;span class=&quot;hljs-built_in&quot;&gt;which&lt;/span&gt; does not implement the `Copy` trait
        5 |     hold_my_vec(v);
          |                 - value moved here
        6 |     &lt;span class=&quot;hljs-built_in&quot;&gt;let&lt;/span&gt; element = v.get(3);
          |                   ^ value borrowed here after move&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The above message tells us that &lt;code&gt;Vec&amp;#x3C;i32&gt;&lt;/code&gt; doesn&apos;t implement &lt;a href=&quot;https://doc.rust-lang.org/std/marker/trait.Copy.html&quot;&gt;the ~Copy~ trait&lt;/a&gt;, and as such must be moved (or borrowed). The &lt;code&gt;Copy&lt;/code&gt; trait is only implementable by data types that can be put on the stack, and because &lt;code&gt;Vec&lt;/code&gt; must go on the heap, it cannot implement &lt;code&gt;Copy&lt;/code&gt;. We need to find another way around this.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Attack of the clones&lt;/h3&gt;&lt;p&gt;Even though a &lt;code&gt;Vec&lt;/code&gt; can&apos;t implement the &lt;code&gt;Copy&lt;/code&gt; trait, it can (and does) implement &lt;a href=&quot;https://doc.rust-lang.org/core/clone/trait.Clone.html&quot;&gt;the ~Clone~ trait&lt;/a&gt;. In Rust, cloning is another way to make duplicates of data. But while copying can only be done on stack-based values and is always very cheap, cloning also works on heap-based values and can be very expensive.&lt;/p&gt;&lt;p&gt;So if the function takes ownership of the value, why don&apos;t we just give it a clone of our vector? That&apos;ll make it happy, right? Indeed, the below code works just fine.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;hold_my_vec&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T&gt;(_: &lt;span class=&quot;hljs-built_in&quot;&gt;Vec&lt;/span&gt;&amp;#x3C;T&gt;) {}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; v = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;7&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;11&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;13&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;17&lt;/span&gt;];
    hold_my_vec(v.clone());
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; element = v.get(&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;);

    &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;I got this element from the vector: {:?}&quot;&lt;/span&gt;, element);
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;However, we have now done a lot of extra work for nothing! The &lt;code&gt;hold_my_vec&lt;/code&gt; function doesn&apos;t even use the vector for anything; it just takes ownership of it. In this case, our vector (&lt;code&gt;v&lt;/code&gt;) is pretty small, so it&apos;s not a big deal to clone it, and in the just-getting-things-to-work-stage of development this may be the quickest and easiest way to see results. However, there is a better, more idiomatic way to do this. Let&apos;s have a look.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;References&lt;/h3&gt;&lt;p&gt;As mentioned previously, rather than giving away our variable to the other function, we can lend it to them. To do this, we need to change the signature of &lt;code&gt;hold_my_vec&lt;/code&gt; to instead accept a reference by changing the type of the incoming parameter from &lt;code&gt;Vec&amp;#x3C;T&gt;&lt;/code&gt; to &lt;code&gt;&amp;#x26;Vec&amp;#x3C;T&gt;&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;We also need to change how we call the function and let Rust know that we&apos;re only giving the function a reference: a borrowed value. This way, we let the function borrow the vector for a little bit, but make sure that we get it back before continuing the program:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;hold_my_vec&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T&gt;(_: &amp;#x26;&lt;span class=&quot;hljs-built_in&quot;&gt;Vec&lt;/span&gt;&amp;#x3C;T&gt;) {}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; v = &lt;span class=&quot;hljs-built_in&quot;&gt;vec!&lt;/span&gt;[&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;7&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;11&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;13&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;17&lt;/span&gt;];
    hold_my_vec(&amp;#x26;v);
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; element = v.get(&lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;);

    &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;I got this element from the vector: {:?}&quot;&lt;/span&gt;, element);
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Summary&lt;/h2&gt;&lt;p&gt;It&apos;s worth noting that this is only a very brief overview of the borrow checker, what it does, and why it does it. A lot of the finer details have been left out to make this article as easy to digest as possible.&lt;/p&gt;&lt;p&gt;Often, as your programs grow, you&apos;ll find more intricate problems that require more thinking and fiddling with ownership and borrows. Oftentimes you&apos;ll even have to rethink how you&apos;ve structured your program to make it work with Rust&apos;s borrow checker. It&apos;s a learning curve, for sure, but if you stick around and make your way to the top, you&apos;re sure to have learned a thing or two about memory along the way.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[New domain: blog.thomasheartman.com]]></title><description><![CDATA[In which I formally deprecate thomashartmann.dev in favor of blog.thomasheartman.com and urge any readers wishing to stay abreast of my writings to subscribe to the new RSS feed.]]></description><link>https://blog.thomasheartman.com/posts/new-domain-blogthomasheartmancom</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/new-domain-blogthomasheartmancom</guid><pubDate>Sun, 12 Jul 2020 18:47:25 GMT</pubDate><content:encoded>&lt;p&gt;This is a heads-up to anyone subscribed to thomashartmann.dev&apos;s RSS feed: I recently acquired the &apos;thomasheartman.com&apos; domain and have moved my blog over to &lt;a href=&quot;https://blog.thomasheartman.com&quot;&gt;blog.thomasheartman.com&lt;/a&gt;. The new RSS feed can be found at &lt;a href=&quot;https://blog.thomasheartman.com/rss.xml&quot;&gt;blog.thomasheartman.com/rss.xml&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;If you have been reading my posts on my website recently, you should have been silently redirected to the new domain. With this post, this behavior is now made explicit. If you&apos;re reading this on the web (as opposed to in some sort of feed reader), you should also find that the URL says blog.thomasheartman.com, regardless of which site you accessed.&lt;/p&gt;&lt;p&gt;I&apos;ll leave thomashartmann.dev up and running to catch and redirect any potential traffic to blog.thomasheartman.com, but once this post is up, nothing else will get published to the former.&lt;/p&gt;</content:encoded></item><item><title><![CDATA[Notmuch: (un)tag outgoing mail]]></title><description><![CDATA[In which we explore the mysteries of notmuch tagging outbound mail as 'unread' and 'inbox' (as if we haven't just written and sent it *out*), and find a simple solution after more effort than we expected.]]></description><link>https://blog.thomasheartman.com/posts/notmuch-(un)tag-outgoing-mail</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/notmuch-(un)tag-outgoing-mail</guid><pubDate>Sun, 12 Jul 2020 13:58:48 GMT</pubDate><content:encoded>&lt;p&gt;I&apos;m here to save past me from spending hours searching the internet for information on how to make notmuch (the Emacs client, specifically) not apply default tags to outgoing mail.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The problem&lt;/h2&gt;&lt;p&gt;So you&apos;ve managed to set up &lt;a href=&quot;https://www.offlineimap.org/&quot;&gt;OfflineIMAP&lt;/a&gt; to fetch mail from your server and you&apos;ve set up &lt;a href=&quot;https://marlam.de/msmtp/&quot;&gt;msmtp&lt;/a&gt; to be able to send mail. It&apos;s taken hours (many more than you care to admit), but you&apos;ve finally got a functioning email client directly embedded in Emacs! This is a good day! You celebrate by firing off an email to another email account you&apos;ve got set up and ... &lt;i&gt;what&apos;s this?&lt;/i&gt; You&apos;ve got an unread email from yourself in your inbox?&lt;/p&gt;&lt;p&gt;On closer inspection, you realize it&apos;s the one you just sent off. But why is it in your inbox? And why is it tagged &apos;unread&apos;?&lt;/p&gt;&lt;pre class=&quot;aside&quot;&gt;Notmuch is a tag-based email system. Rather than folders, everything is done
through tagging, filtering, and searching. As such, your &apos;inbox&apos; is just all
mail that&apos;s tagged &apos;inbox&apos;.&lt;/pre&gt;&lt;p&gt;You check your &lt;code&gt;.notmuch-config&lt;/code&gt; and find that you&apos;ve told notmuch to automatically tag new mail (pulled from the server) with &apos;inbox&apos; and &apos;unread&apos;. This makes sense, you think to yourself. After all, you&apos;d like to get new mail into your inbox and you&apos;d like it to be marked as unread. But why would notmuch apply the same tags to outgoing mail?&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The solution&lt;/h2&gt;&lt;p&gt;After spending hours trying to make notmuch&apos;s post-insert hook work (and still not quite understanding that one), you decide to check out where sent mail is stored, thinking you could use the location to filter the email that gets processed by the &lt;code&gt;[new]&lt;/code&gt; section of your config. You remember reading that it relates to the &apos;Fcc&apos; field, so you check out the description for the variable &lt;code&gt;notmuch-fcc-dirs&lt;/code&gt; and find this nugget:&lt;/p&gt;&lt;blockquote&gt;[...] the header should be of the form &quot;folder +tag1 -tag2&quot; where folder is
the folder (relative to the notmuch mailstore) to store the message in, and
tag1 and tag2 are tag changes to apply to the stored message.&lt;/blockquote&gt;&lt;p&gt;Can it really be that simple? Is that really it?! All these hours for &lt;i&gt;that&lt;/i&gt;? You set it to &lt;code&gt;sent -unread -inbox&lt;/code&gt; and fire off an email.&lt;/p&gt;&lt;p&gt;...&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Yup&lt;/strong&gt;. That&apos;s it. Your message template now looks like this and behaves the way you want it to, both removing &apos;unread&apos; and &apos;inbox&apos; tags &lt;i&gt;and&lt;/i&gt; adding a &apos;sent&apos; tag so you can easily see all your sent mail:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;From: Your Name &amp;#x26;lt;yourname@provider.tld&amp;#x26;gt;
To:
Subject:
Fcc: sent +sent -unread -inbox
--text follows this line--&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[org-babel-load-file doesn't tangle correctly]]></title><description><![CDATA[The `org-babel-load-file` function to automatically tangle and load org files with emacs lisp in them has a quirk that sometimes causes some code blocks to not tangle properly. The solution is to use `emacs-lisp` instead of `elisp` for your code blocks.]]></description><link>https://blog.thomasheartman.com/posts/org-babel-load-file-doesnt-tangle-correctly</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/org-babel-load-file-doesnt-tangle-correctly</guid><pubDate>Thu, 21 May 2020 19:52:19 GMT</pubDate><content:encoded>&lt;p&gt;I recently started &lt;a href=&quot;https://blog.thomasheartman.com/blog/configuring-emacs-with-org-mode-and-literate-programming&quot;&gt;using Org mode for configuring Emacs&lt;/a&gt; and I really like it. However, I did run into an issue where, for some reason, &lt;code&gt;org-babel-load-file&lt;/code&gt; didn&apos;t seem to update the tangled version of the file.&lt;/p&gt;&lt;p&gt;I thought perhaps it was an issue with caching at first, because if I manually tangled the file, everything would be just as I expected. However, if I started another instance of Emacs, it would re-evaluate the &lt;code&gt;org-babel-load-file&lt;/code&gt; function, and I would end up with the wrong version of the file again.&lt;/p&gt;&lt;p&gt;I couldn&apos;t quite understand what was going on, but found the answer in a stack overflow post that I have sadly lost the link to: In Org mode, the official code for Emacs Lisp is &lt;code&gt;emacs-lisp&lt;/code&gt;, but for code blocks, it also accepts &lt;code&gt;elisp&lt;/code&gt;. From what I understand, &lt;code&gt;elisp&lt;/code&gt; is set up as an alias for &lt;code&gt;emacs-lisp&lt;/code&gt;. This seems to apply to manual tangling too, but not to &lt;code&gt;org-babel-load-file&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;And sure enough, I&apos;d started using &lt;code&gt;elisp&lt;/code&gt; instead of &lt;code&gt;emacs-lisp&lt;/code&gt; partway through my config and those blocks wouldn&apos;t get tangled by &lt;code&gt;org-babel-load-file&lt;/code&gt;. Going through and updating the blocks to use &lt;code&gt;emacs-lisp&lt;/code&gt; instead of &lt;code&gt;elisp&lt;/code&gt; was enough to get everything working again.&lt;/p&gt;&lt;p&gt;While the fix turned out to be simple, it was hard to find. So I&apos;ll leave this here, hoping it saves someone some time and effort in the future.&lt;/p&gt;&lt;p&gt;Remember: use &lt;code&gt;#+begin_src emacs-lisp&lt;/code&gt; and not &lt;code&gt;#+begin_src elisp&lt;/code&gt;.&lt;/p&gt;</content:encoded></item><item><title><![CDATA[70,000 words]]></title><description><![CDATA[In which I look back upon the last year and what I've achieved with the blog. Mostly a meta-post, there's a selection of statistics as well as some general thoughts on what it's been like to write every week for a year.]]></description><link>https://blog.thomasheartman.com/posts/70000-words</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/70000-words</guid><pubDate>Mon, 18 May 2020 20:41:10 GMT</pubDate><content:encoded>&lt;p&gt;Today marks a personal achievement of mine. A year ago, on May 18th 2019, I published the first post in a year-long chain of weekly content.&lt;/p&gt;&lt;p&gt;The decision to put something out every week was motivated in part by the words of &lt;a href=&quot;https://www.hanselman.com/&quot;&gt;Scott Hanselman&lt;/a&gt;, who says the most important thing is regularity. It doesn&apos;t matter if it&apos;s not stellar every time, as long as you&apos;re regular. As long as people can expect new content from you at regular intervals, you&apos;ll build a following.&lt;/p&gt;&lt;p&gt;Another important factor was this: if you force yourself to create and release content every week for a year, you &lt;i&gt;will&lt;/i&gt; get better at it. Not only will you get better at writing and expressing yourself, but you will also learn to accept that things are never perfect and that you can (and must) release something nonetheless. You can&apos;t hold on to something until it is perfect, because it never will be. Learning to accept this is a key part of being a creator.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The ups and downs&lt;/h2&gt;&lt;p&gt;As with everything else, committing to a weekly writing schedule has its share upsides and downsides. While finding a topic to write about every week is surprisingly easy, doing the research and putting words on the page is surprisingly hard and time-consuming.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;The Good&lt;/h3&gt;&lt;p&gt;The most obvious positive is that I&apos;ve gotten a lot of writing practice. I&apos;ve also gained some exposure within certain programming communities, and I&apos;ve learned a lot about a wide variety of topics.&lt;/p&gt;&lt;p&gt;The most valuable thing, however, may be that I now have a body of work available on the internet. It may sound silly, but the satisfaction I get from looking back at how far I&apos;ve come and how much I&apos;ve produced is not to be understated.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;The Bad&lt;/h3&gt;&lt;p&gt;Time. Writing takes time. Writing takes a lot of time. Writing takes even more time when you are a bit of perfectionist and want to make sure everything is &lt;i&gt;just right&lt;/i&gt; ™.&lt;/p&gt;&lt;p&gt;I estimate that I&apos;ve spent, on average, about a work day on each post. That makes over four hundred hours in the past year and is equivalent to a little over 10 weeks worth of work, assuming a work week of about 40 hours.&lt;/p&gt;&lt;p&gt;This is a pretty serious cost. I can&apos;t remember the last time I had full weekend off. Sometimes you just want to relax, but you can&apos;t because you know you have to write that next post. It hasn&apos;t always been fun. I haven&apos;t always wanted to do this, but I&apos;ve pushed through.&lt;/p&gt;&lt;p&gt;I&apos;ve also set myself an increasingly high bar and specialized in a few key areas. I&apos;ve created a system where it feels as if every post has to be of a certain length and about a certain topic. This has kept me from writing shorter posts and from exploring other topics, such as CSS and the .NET ecosystem, for instance.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Tangible outcomes&lt;/h2&gt;&lt;p&gt;What do you get out of pouring all these hours and all this effort into a blog like this? Personal satisfaction and a feeling of accomplishment is one thing, but have I gotten anything tangible in return for my efforts?&lt;/p&gt;&lt;p&gt;Let&apos;s see:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Newsletters and reading lists&lt;/dt&gt;&lt;dd&gt;I&apos;ve had posts featured on a number of weekly newsletters, including &lt;a href=&quot;https://this-week-in-rust.org/&quot;&gt;This Week in Rust&lt;/a&gt;, &lt;a href=&quot;https://haskellweekly.news/&quot;&gt;Haskell Weekly&lt;/a&gt;, and &lt;a href=&quot;https://weekly.nixos.org/&quot;&gt;NixOS Weekly&lt;/a&gt;. As an avid reader of all of these, it&apos;s been a joy to see my name on the lists. I&apos;ve also often seen links from other reading lists, such as &lt;a href=&quot;https://readrust.net/&quot;&gt;Read Rust&lt;/a&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Rust release notes&lt;/dt&gt;&lt;dd&gt;And speaking of Rust, my post on &lt;a href=&quot;https://blog.thomasheartman.com/blog/feature(slice_patterns)/&quot;&gt;advanced slice patterns&lt;/a&gt; got a special mention in the &lt;a href=&quot;https://blog.rust-lang.org/2020/03/12/Rust-1.42.html&quot;&gt;release notes for 1.42&lt;/a&gt;. Big, proud crab moment 🦀&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Freelancer agreements&lt;/dt&gt;&lt;dd&gt;Off the back of the post mentioned above, I was recently contacted by (and subsequently signed a contract with) an external company to write content for their blog. By definition, I&apos;m now a professional writer.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Being able to look up my own knowledge&lt;/dt&gt;&lt;dd&gt;More than a few times, I&apos;ve found myself trying to recall how to use a specific &lt;a href=&quot;https://blog.thomasheartman.com/tags/git&quot;&gt;git command&lt;/a&gt; or just &lt;a href=&quot;https://blog.thomasheartman.com/posts/command-line-control-awk&quot;&gt;how awk&apos;s syntax works&lt;/a&gt;. At times like these, knowing I&apos;ve written about it previously makes it very easy to quickly find what I&apos;ve forgotten. This also matches how I&apos;ve often heard other content creators say that they end up finding their own content when looking up how to do something.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Conference talks&lt;/dt&gt;&lt;dd&gt;I&apos;m speaking at NDC Oslo this year. I don&apos;t know whether the blog played any part in me landing the spot or not, but I like to think that it might have. At the very least, I don&apos;t think it hurt.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Stats&lt;/h3&gt;&lt;p&gt;In addition to the outcomes mentioned above, I thought it&apos;d be interesting to present some statistics on what I&apos;ve published so far (before this post).&lt;/p&gt;&lt;ul&gt;&lt;div&gt;&lt;dt&gt;Total number of published words&lt;/dt&gt;&lt;dd&gt;71,554&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Total number of posts&lt;/dt&gt;&lt;dd&gt;53&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Average word count&lt;/dt&gt;&lt;dd&gt;1,350&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Longest post&lt;/dt&gt;&lt;dd&gt;&lt;a href=&quot;https://blog.thomasheartman.com/blog/lets-read-haskell-programming-from-first-principles-pt-iv&quot;&gt;Let&apos;s Read Haskell Programming from First Principles, part IV: Basic data types&lt;/a&gt; (2,866 words)&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Shortest post&lt;/dt&gt;&lt;dd&gt;&lt;a href=&quot;https://blog.thomasheartman.com/blog/rebasing-off-a-repo-root&quot;&gt;Rebasing off a repo root&lt;/a&gt; (277 words)&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Number of unique tags&lt;/dt&gt;&lt;dd&gt;34&lt;/dd&gt;&lt;/div&gt;&lt;li&gt;Most used tags ::&lt;/li&gt;&lt;ol&gt;&lt;li&gt;&lt;a href=&quot;https://blog.thomasheartman.com/tags/haskell&quot;&gt;Haskell&lt;/a&gt; (15 posts)&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://blog.thomasheartman.com/tags/git&quot;&gt;Git&lt;/a&gt; (10 posts)&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://blog.thomasheartman.com/tags/rust&quot;&gt;Rust&lt;/a&gt; (7 posts)&lt;/li&gt;&lt;/ol&gt;&lt;div&gt;&lt;dt&gt;Time spent&lt;/dt&gt;&lt;dd&gt;400+ hours&lt;/dd&gt;&lt;/div&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Traffic generators&lt;/h3&gt;&lt;p&gt;I use Netlify&apos;s analytics to get a rough overview over how many page views I get and to see what content gets the most traffic. Based entirely on anecdotal experience from checking my numbers every now and then, I can tell you that Rust is far and away what generates the most views on my blog. At the time of writing, the four most visited blog posts are all Rust posts.&lt;/p&gt;&lt;p&gt;The post on &lt;a href=&quot;https://blog.thomasheartman.com/blog/improve-your-workflow-with-forge&quot;&gt;Magit Forge&lt;/a&gt; also performed very well and got some pretty good circulation (in relative terms) on Twitter.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Now what?&lt;/h2&gt;&lt;p&gt;Now that I&apos;ve reached my goal and completed the year of blogging, what&apos;s next for the blog? Do I just drop it? Do I keep it up? Do I put even more time into it?&lt;/p&gt;&lt;p&gt;I have no intentions of letting the blog go any time soon. However, I &lt;i&gt;do&lt;/i&gt; intend to change up the format a bit. I&apos;d like experiment more with shorter posts and different kinds of content.&lt;/p&gt;&lt;p&gt;I also expect not to write much in the next month, as I&apos;d like to focus much more on &lt;a href=&quot;https://ndcoslo.com/talk/getting-your-feet-wet-with-open-source/&quot;&gt;the talk I&apos;ll be giving at NDC Oslo in June&lt;/a&gt;. I&apos;d say a little time off is well deserved.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Was it worth it?&lt;/h2&gt;&lt;p&gt;&lt;a href=&quot;https://chriscoyier.net/&quot;&gt;Chris Coyier&lt;/a&gt; has said that the best way to create a name for yourself online is to write. Write, write, and then write some more. Content is valuable, and you can always offer something new and unique.&lt;/p&gt;&lt;p&gt;Words like these motivate me, and when I look back upon what I&apos;ve written so far, I&apos;m even more motivated to keep going. I&apos;ve got so much more to learn and so much more to say.&lt;/p&gt;&lt;p&gt;So yes, it was worth it.&lt;/p&gt;&lt;p&gt;Now excuse me while I go play some video games.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[The results of splitting empty strings]]></title><description><![CDATA[In which we talk at length about string splitting in various languages and how to handle the cases where the string is empty or where the separator doesn't appear in the string. As an interesting side note, we also briefly explore what happens if you use an empty separator.]]></description><link>https://blog.thomasheartman.com/posts/the-results-of-splitting-empty-strings</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/the-results-of-splitting-empty-strings</guid><pubDate>Mon, 11 May 2020 07:28:25 GMT</pubDate><content:encoded>&lt;p&gt;What should a function splitting an empty string return? What about splitting a string on a separator that does not exist within the string? This was the topic of some debate within my team recently, when one of my teammates had assumed that splitting an empty string on a separator would return an empty list. It does not&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Splitting on a substring that doesn&apos;t appear in the string&lt;/h2&gt;&lt;p&gt;When you split a string an arbitrary number of times, it&apos;s reasonable to expect to find yourself with a list of all the pieces. If you were to join all these pieces back together using the same separator that you used to split the original string, you should arrive back at where you started. In other words, if &lt;code&gt;sep&lt;/code&gt; is an arbitrary separator, then the following bit of pseudocode should be true: &lt;code&gt;originalString == originalString.split(sep).join(sep)&lt;/code&gt;.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;The algorithmic approach&lt;/h3&gt;&lt;p&gt;Given a string and a separator, we can describe a string splitting algorithm in two, simple steps:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Take everything up until the separator and append it to the list of substrings. If you don&apos;t find the separator, add the whole string to the list.&lt;/li&gt;&lt;li&gt;Take what&apos;s left of the string after the separator, and go back to step one, using the remaining part of the string as input.&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;When there is no more string to split, you&apos;ve completed the substring list and can return that to the caller.&lt;/p&gt;&lt;p&gt;Adding the whole string to the list if you don&apos;t find the separator is a crucial part of step one. Without it, you would never get the final piece of a string. If you split &quot;I fell asleep&quot; on spaces, you&apos;d expect to get &lt;code&gt;[&quot;I&quot;, &quot;fell&quot;, &quot;asleep&quot;]&lt;/code&gt; in return. But if you discard a string if it doesn&apos;t have the separator, you&apos;d end up with only ~[&quot;I&quot;, &quot;fell&quot;]~; a very different outcome.&lt;/p&gt;&lt;p&gt;If the separator doesn&apos;t appear in the string at all, we simply add the whole string as the first element of the list and consider our work done. This way, the function is internally consistent. As you go through the string, you will always eventually reach a substring that doesn&apos;t contain the separator. That substring is also part of the result.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;The user experience approach&lt;/h3&gt;&lt;p&gt;There&apos;s another angle to come at this from: as the end user. What would you, the developer using the function, expect it to return? This is a subjective thing, so I can only really speak for myself, but if I know that if a function always returns data of the same shape (such as a list), I find it much easier to work with.&lt;/p&gt;&lt;p&gt;What if the string doesn&apos;t contain the separator at all? Well, then it can&apos;t be split. Imagine we&apos;re cooking together. I give you some carrots and ask you to cut the tops off. What do you do if one of the carrots has already had the top cut off? You&apos;d probably realize it doesn&apos;t need anything done to it, and put it in the done-pile with the others.&lt;/p&gt;&lt;p&gt;Similarly, a string that has no separator (no top) need not be split, and you can just return it as-is.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Splitting an empty string&lt;/h2&gt;&lt;p&gt;Splitting an empty string isn&apos;t any different than what we&apos;ve already explored. In fact, it&apos;s just a more specialized version of the above problem. It can also come up if the string you&apos;re splitting ends with the separator. For instance &quot;juice,&quot;  split on commas, would be &lt;code&gt;[&quot;juice&quot;, &quot;&quot;]&lt;/code&gt;. An empty string is still a string.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The empty string as separator&lt;/h2&gt;&lt;p&gt;What if the separator is an empty string? This varies from language to language. For instance, in JavaScript, an empty string as separator means &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split&quot;&gt;&apos;split the string into a list of characters&apos;&lt;/a&gt;, while Python throws an exception. Rust&apos;s &lt;code&gt;split&lt;/code&gt; splits the string into a list of one-character strings (like JavaScript does), but inserts an empty string at the start and at the end (&lt;a href=&quot;https://play.rust-lang.org/?version=stable&amp;#x26;mode=debug&amp;#x26;edition=2018&amp;#x26;gist=72f66ec6489c9efa03835b1a921b6178&quot;&gt;playground link&lt;/a&gt;).&lt;/p&gt;&lt;p&gt;What does it even mean to use an empty string as a separator? There&apos;s no clear answer here, so it&apos;s at your discretion as the function author. For instance, a Haskell-implementation I quickly threw together while writing this post&lt;sup id=&quot;fnr-2&quot; class=&quot;footnote-ref&quot; data-label=&quot;2&quot;&gt;&lt;a href=&quot;#fn-2&quot;&gt;[2]&lt;/a&gt;&lt;/sup&gt; returns an infinite list of empty strings. I&apos;m inclined to say that that&apos;s reasonable, but it&apos;s probably not very useful.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Summary&lt;/h2&gt;&lt;p&gt;There&apos;s any number of ways to slice a string. Most languages seem to follow the idea that splitting a string gives you back a list of substrings, even if the string is empty or the separator doesn&apos;t appear in the string at all. The disagreement is about what to do with an empty separator, but at least they all agree on it being a special case.&lt;/p&gt;&lt;p&gt;If you&apos;re feeling the urge come over you after all this, then how about taking a stab at implementing a string splitting algorithm yourself? It&apos;s quite the fun, little exercise if you&apos;re looking for something to occupy your mind for a bit.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;/div&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;This particular case was in JavaScript, where splitting using an empty string as the separator &lt;i&gt;will&lt;/i&gt; actually return an empty list given an empty string (~&apos;&apos;.split(&apos;&apos;)~ returns &lt;code&gt;[]&lt;/code&gt;), but this is a special case. Most languages (and their standard functions), that I&apos;m aware of, require you to opt in to remove empty strings from the output, though there are outliers.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[2]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-2&quot; class=&quot;footnote&quot; data-label=&quot;2&quot;&gt;&lt;p&gt;The implementation is included here for the particularly interested reader:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;split&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt; -&gt; [&lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt;]
&lt;span class=&quot;hljs-title&quot;&gt;split&lt;/span&gt; sep input =
  go &lt;span class=&quot;hljs-string&quot;&gt;&quot;&quot;&lt;/span&gt; (&lt;span class=&quot;hljs-type&quot;&gt;Just&lt;/span&gt; input)
  &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt; go before remaining =
          &lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; remaining &lt;span class=&quot;hljs-keyword&quot;&gt;of&lt;/span&gt;
            &lt;span class=&quot;hljs-type&quot;&gt;Nothing&lt;/span&gt; -&gt; [before]
            &lt;span class=&quot;hljs-type&quot;&gt;Just&lt;/span&gt;(s) -&gt;
              &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; take (length sep) s == sep
              &lt;span class=&quot;hljs-keyword&quot;&gt;then&lt;/span&gt; before : (go &lt;span class=&quot;hljs-string&quot;&gt;&quot;&quot;&lt;/span&gt; $ &lt;span class=&quot;hljs-type&quot;&gt;Just&lt;/span&gt; $ drop (length sep) s)
              &lt;span class=&quot;hljs-keyword&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; s &lt;span class=&quot;hljs-keyword&quot;&gt;of&lt;/span&gt;
                &lt;span class=&quot;hljs-string&quot;&gt;&quot;&quot;&lt;/span&gt; -&gt; go before &lt;span class=&quot;hljs-type&quot;&gt;Nothing&lt;/span&gt;
                (c:cs) -&gt; go (before ++ [c]) $ &lt;span class=&quot;hljs-type&quot;&gt;Just&lt;/span&gt; cs&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dl id=&quot;footnotes&quot;&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;This particular case was in JavaScript, where splitting using an empty string as the separator &lt;i&gt;will&lt;/i&gt; actually return an empty list given an empty string (~&apos;&apos;.split(&apos;&apos;)~ returns &lt;code&gt;[]&lt;/code&gt;), but this is a special case. Most languages (and their standard functions), that I&apos;m aware of, require you to opt in to remove empty strings from the output, though there are outliers.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[2]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-2&quot; class=&quot;footnote&quot; data-label=&quot;2&quot;&gt;&lt;p&gt;The implementation is included here for the particularly interested reader:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;split&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt; -&gt; [&lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt;]
&lt;span class=&quot;hljs-title&quot;&gt;split&lt;/span&gt; sep input =
  go &lt;span class=&quot;hljs-string&quot;&gt;&quot;&quot;&lt;/span&gt; (&lt;span class=&quot;hljs-type&quot;&gt;Just&lt;/span&gt; input)
  &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt; go before remaining =
          &lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; remaining &lt;span class=&quot;hljs-keyword&quot;&gt;of&lt;/span&gt;
            &lt;span class=&quot;hljs-type&quot;&gt;Nothing&lt;/span&gt; -&gt; [before]
            &lt;span class=&quot;hljs-type&quot;&gt;Just&lt;/span&gt;(s) -&gt;
              &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; take (length sep) s == sep
              &lt;span class=&quot;hljs-keyword&quot;&gt;then&lt;/span&gt; before : (go &lt;span class=&quot;hljs-string&quot;&gt;&quot;&quot;&lt;/span&gt; $ &lt;span class=&quot;hljs-type&quot;&gt;Just&lt;/span&gt; $ drop (length sep) s)
              &lt;span class=&quot;hljs-keyword&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; s &lt;span class=&quot;hljs-keyword&quot;&gt;of&lt;/span&gt;
                &lt;span class=&quot;hljs-string&quot;&gt;&quot;&quot;&lt;/span&gt; -&gt; go before &lt;span class=&quot;hljs-type&quot;&gt;Nothing&lt;/span&gt;
                (c:cs) -&gt; go (before ++ [c]) $ &lt;span class=&quot;hljs-type&quot;&gt;Just&lt;/span&gt; cs&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/dd&gt;&lt;/dl&gt;</content:encoded></item><item><title><![CDATA[Save on typing and improve legibility with Rust's macros]]></title><description><![CDATA[I finally took the time to learn the very basics of Rust's declarative macros this past week and learned a lot. This post acts as a basic introduction to Rust macros as I understand them now.]]></description><link>https://blog.thomasheartman.com/posts/save-on-typing-and-improve-legibility-with-rusts-macros</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/save-on-typing-and-improve-legibility-with-rusts-macros</guid><pubDate>Mon, 04 May 2020 07:54:28 GMT</pubDate><content:encoded>&lt;p&gt;I found some spare time this past week and sat down with a nice brew and &lt;a href=&quot;https://thesquareplanet.com/&quot;&gt;Jon Gjengset&lt;/a&gt;&apos;s excellent &lt;a href=&quot;https://youtu.be/q6paRBbLgNw&quot;&gt;Crust of Rust video on declarative macros&lt;/a&gt;. For the longest time, macros have felt &apos;that last part of Rust that I haven&apos;t gotten around to checking out&apos;. I&apos;ve had a vague notion of what they are, but have never quite gotten to exploring them. However, Gjengset&apos;s video served as a perfect introduction to declarative macros, and was just enough to get me started.&lt;/p&gt;&lt;p&gt;One thing that was mentioned in the video that I have never thought about before, is that one of the simplest things to do with macros is simple substitution. In fact, that&apos;s all a declarative macro can do: given some input, it&apos;ll expand to a block of code. That suddenly gave me an idea for writing my own first macro.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Post purpose&lt;/h2&gt;&lt;p&gt;This post is intended to be a very brief and basic introduction to declarative macros based on what have I found in the past week. For more comprehensive material, see the &apos;Further Reading&apos; section at the end.&lt;/p&gt;&lt;p&gt;The post describes one very simple use case for macros, and that&apos;s all it&apos;s intended to do. In particular, this post will &lt;strong&gt;not&lt;/strong&gt; disccuss&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;macro syntax&lt;/dt&gt;&lt;dd&gt;There will be no talk of &lt;a href=&quot;https://danielkeep.github.io/tlborm/book/mbe-macro-rules.html&quot;&gt;macro syntax&lt;/a&gt;, of &lt;a href=&quot;https://danielkeep.github.io/tlborm/book/mbe-macro-rules.html#captures&quot;&gt;capture kinds and patterns&lt;/a&gt;, or of &lt;a href=&quot;https://danielkeep.github.io/tlborm/book/blk-counting.html&quot;&gt;clever ways to count&lt;/a&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;other use cases&lt;/dt&gt;&lt;dd&gt;This is not an exploration of all the ways in which you can use declarative macros or where they shine. This is a description of one case that solved a problem that&apos;s been irking me.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;proc macros&lt;/dt&gt;&lt;dd&gt;&lt;a href=&quot;https://doc.rust-lang.org/book/ch19-06-macros.html#procedural-macros-for-generating-code-from-attributes&quot;&gt;Proc macros&lt;/a&gt; are a different subject, and is something I don&apos;t know much (or anything, really) about. They&apos;re both a form of metaprogramming, but from what I understand, proc macros are quite a bit more complex than declarative macros (and thus more powerful), so it&apos;s best left for later.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;I assume a basic level of familiarity with Rust, but a deep understanding is not required.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;My Little Macro 🦄&lt;/h2&gt;&lt;p&gt;I &lt;a href=&quot;https://blog.thomasheartman.com/posts/feature(slice_patterns)/&quot;&gt;was very excited&lt;/a&gt; when advanced slice patterns were stabilized in Rust 1.42. Among the things I&apos;d been looking forward to was the ability to match on strings as if they were a slice of characters, similar to what you might do in Haskell or Elm. It &lt;a href=&quot;https://www.reddit.com/r/rust/comments/f4usb4/pattern_matching_on_string_content_as_chars/&quot;&gt;wasn&apos;t immediately obvious&lt;/a&gt; how to do it, but &lt;a href=&quot;https://www.reddit.com/r/rust/comments/f4usb4/pattern_matching_on_string_content_as_chars/fhy8dmc&quot;&gt;I figured something out in the end&lt;/a&gt;&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt;&lt;/span&gt;(s: &amp;#x26;&lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;) {
    &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; &amp;#x26;s.chars().collect::&amp;#x3C;&lt;span class=&quot;hljs-built_in&quot;&gt;Vec&lt;/span&gt;&amp;#x3C;&lt;span class=&quot;hljs-built_in&quot;&gt;char&lt;/span&gt;&gt;&gt;() &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; &amp;#x26;[&lt;span class=&quot;hljs-built_in&quot;&gt;char&lt;/span&gt;] {
        [&apos;💘&apos;, .., &apos;🦄&apos;] =&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;&amp;#x3C;3 and horse&quot;&lt;/span&gt;),
        [&apos;💘&apos;, snd, .., &apos;😪&apos;] =&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;Love, {}, and sleeps&quot;&lt;/span&gt;, snd),
        [&apos;💘&apos;, ..] =&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;Just &amp;#x3C;3&quot;&lt;/span&gt;),
        _ =&gt; {}
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;However, it&apos;s not immediately obvious what&apos;s happening on line 2: what exactly does &lt;code&gt;&amp;#x26;s.chars().collect::&amp;#x3C;Vec&amp;#x3C;char&gt;&gt;() as &amp;#x26;[char]&lt;/code&gt; mean? Sure, I can tell you that it turns the string into a &lt;code&gt;char&lt;/code&gt; slice for matching, but as it stands, it&apos;s quite the mouthful. Let&apos;s write a macro to make this cleaner and clearer!&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Replacement as a form of abstraction&lt;/h3&gt;&lt;p&gt;Because a declarative macro is nothing but text substitution&lt;sup id=&quot;fnr-2&quot; class=&quot;footnote-ref&quot; data-label=&quot;2&quot;&gt;&lt;a href=&quot;#fn-2&quot;&gt;[2]&lt;/a&gt;&lt;/sup&gt;, we should be able to simply abstract away the pesky line from above. Instead, we want to write something like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt;&lt;/span&gt;(s: &amp;#x26;&lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;) {
    &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; chars!(s) {
        [&apos;💘&apos;, .., &apos;🦄&apos;] =&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;&amp;#x3C;3 and horse&quot;&lt;/span&gt;),
        [&apos;💘&apos;, snd, .., &apos;😪&apos;] =&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;Love, {}, and sleeps&quot;&lt;/span&gt;, snd),
        [&apos;💘&apos;, ..] =&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;Just &amp;#x3C;3&quot;&lt;/span&gt;),
        _ =&gt; {}
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;To do this, we write a very simple macro with a single pattern:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;macro_rules!&lt;/span&gt; chars {
    ($s:expr) =&gt; {
        &amp;#x26;$s.chars().collect::&amp;#x3C;&lt;span class=&quot;hljs-built_in&quot;&gt;Vec&lt;/span&gt;&amp;#x3C;&lt;span class=&quot;hljs-built_in&quot;&gt;char&lt;/span&gt;&gt;&gt;() &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; &amp;#x26;[&lt;span class=&quot;hljs-built_in&quot;&gt;char&lt;/span&gt;]
    };
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;All it does is replace the macro call (&lt;code&gt;chars!(s)&lt;/code&gt;) with the long incantation (&lt;code&gt;&amp;#x26;s.chars().collect::&amp;#x3C;Vec&amp;#x3C;char&gt;&gt;() as &amp;#x26;[char]&lt;/code&gt;) when compiling. It&apos;s incredibly simple, but it&apos;s also incredibly powerful and it&apos;s made the code look less cluttered &lt;i&gt;and&lt;/i&gt; read better at the same time.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Further reading&lt;/h2&gt;&lt;p&gt;If you want to know more about macros, here are some good resources to continue your journey:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;[[https://youtu.be/q6paRBbLgNw][Jon Gjengset&apos;s Crust of Rust: Declarative Macros]]&lt;/dt&gt;&lt;dd&gt;Gjengset spends roughly 90 minutes explaining and demonstrating macros in a very clear fashion by creating a macro that has the same functionality as the standard library&apos;s &lt;code&gt;vec!&lt;/code&gt; macro. If you&apos;re looking for an introduction to what declarative macros are, I absolutely recommend you watch this.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;[[https://danielkeep.github.io/tlborm/book/README.html][The Little Book of Rust Macros]]&lt;/dt&gt;&lt;dd&gt;Gjengset mentions this as a resource in his Crust of Rust video. It&apos;s a thorough intro to macros and includes everything from syntax to patterns to macro building blocks and a guide on how to &lt;a href=&quot;https://danielkeep.github.io/tlborm/book/aeg-ook.html&quot;&gt;implement esoteric languages using only macros&lt;/a&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;[[https://doc.rust-lang.org/book/ch19-06-macros.html][The Book, chapter 19.06]]&lt;/dt&gt;&lt;dd&gt;As always, the Book is a valuable resource on all things Rust. Compared to the previous items on the list, this is much shorter, but it provides a strong high-level overview.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;[[https://doc.rust-lang.org/reference/macros-by-example.html][The Rust Reference on macros]]&lt;/dt&gt;&lt;dd&gt;Probably the densest resource on this list, the Rust Reference provides a short, yet comprehensive reference on macros. If you need to quickly look something up, this is a good bet.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;/div&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;Iterating over a string and collecting it into a vector of characters is probably not the most &lt;i&gt;efficient&lt;/i&gt; way to work with strings, but it&apos;s the best way I&apos;ve found to turn a string into a slice of (UTF-8) characters that can be matched on. If you&apos;ve got a better solution for this, let me know! I&apos;ve been looking for a while.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[2]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-2&quot; class=&quot;footnote&quot; data-label=&quot;2&quot;&gt;&lt;p&gt;Well, saying it&apos;s &lt;i&gt;just&lt;/i&gt; text substitution might be misleading: Because the expanded macro is parsed into the program&apos;s abstract syntax tree, it has to be valid Rust. See &lt;a href=&quot;https://danielkeep.github.io/tlborm/book/mbe-syn-source-analysis.html&quot;&gt;the first chapter of the Little Book of Rust Macros&lt;/a&gt; for more information.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dl id=&quot;footnotes&quot;&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;Iterating over a string and collecting it into a vector of characters is probably not the most &lt;i&gt;efficient&lt;/i&gt; way to work with strings, but it&apos;s the best way I&apos;ve found to turn a string into a slice of (UTF-8) characters that can be matched on. If you&apos;ve got a better solution for this, let me know! I&apos;ve been looking for a while.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[2]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-2&quot; class=&quot;footnote&quot; data-label=&quot;2&quot;&gt;&lt;p&gt;Well, saying it&apos;s &lt;i&gt;just&lt;/i&gt; text substitution might be misleading: Because the expanded macro is parsed into the program&apos;s abstract syntax tree, it has to be valid Rust. See &lt;a href=&quot;https://danielkeep.github.io/tlborm/book/mbe-syn-source-analysis.html&quot;&gt;the first chapter of the Little Book of Rust Macros&lt;/a&gt; for more information.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;/dl&gt;</content:encoded></item><item><title><![CDATA[Configuring Emacs with Org mode and literate programming]]></title><description><![CDATA[In which I share how I recently took my first steps into the world of literate programming via Emacs and Org mode. If you're looking for how to start configuring Emacs with Org mode or just a brief introduction to literate programming, this should be a good place to start.]]></description><link>https://blog.thomasheartman.com/posts/configuring-emacs-with-org-mode-and-literate-programming</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/configuring-emacs-with-org-mode-and-literate-programming</guid><pubDate>Mon, 27 Apr 2020 07:51:14 GMT</pubDate><content:encoded>&lt;p&gt;Even if you have the source code in front of you, there are limits to what a human reader can absorb from thousands of lines of text designed primarily to function, not to convey meaning. --- Ellen Ullman (from &lt;a href=&quot;http://www.literateprogramming.com/quotes_sa.html&quot;&gt;quotes about software aging on literateprogramming.com&lt;/a&gt;)&lt;/p&gt;&lt;p&gt;I&apos;ve been intrigued by &lt;i&gt;literate programming&lt;/i&gt; for a while now, but never quite found the right opportunity to try it out. All the business with &lt;i&gt;tangling&lt;/i&gt; and &lt;i&gt;detangling&lt;/i&gt;, calling code from other snippets, and understanding how or even &lt;i&gt;if&lt;/i&gt; you can import literate code into non-literate code, made it seem like you&apos;d need to understand a lot just to get started. Fortunately, I found something that doesn&apos;t require any of the above: extending your Emacs config.&lt;/p&gt;&lt;p&gt;Using &lt;a href=&quot;https://orgmode.org/worg/org-contrib/babel/&quot;&gt;Org mode&lt;/a&gt; and literate programming to configure Emacs is something I&apos;ve heard a lot about, but I found it difficult to find out exactly how to get started. Luckily it turned out to be pretty simple.&lt;/p&gt;&lt;p&gt;Below, I&apos;ll show you how to start configuring Emacs with Org mode and what I&apos;ve learned about it so far, but if you&apos;re really eager to just get started, the trick is to use the function &lt;code&gt;org-babel-load-file&lt;/code&gt; and give it the path to your Org file.&lt;/p&gt;&lt;pre class=&quot;aside&quot;&gt;*Disclaimer*: I am /not/ an expert at literate programming, or even particularly knowledgeable; these are my first steps into this brave new world. If I&apos;ve made any mistakes or if you&apos;ve got tips: don&apos;t hesitate to reach out.&lt;/pre&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Who is this for?&lt;/h2&gt;&lt;p&gt;This post is aimed at anyone interested in literate programming with Org mode, but who does not know where or how to get started. It assumes some familiarity with Emacs and Org mode, but no further knowledge of programming is required. Further, I assume no prior knowledge of literate programming.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;What is literate programming?&lt;/h2&gt;&lt;blockquote&gt;I believe that the time is ripe for significantly better documentation of programs, and that we can best achieve this by considering programs to be works of literature. Hence, my title: &quot;Literate Programming.&quot;&lt;/blockquote&gt;&lt;p&gt;Those are the words of &lt;a href=&quot;https://en.wikipedia.org/wiki/Donald_Knuth&quot;&gt;Donald Knuth&lt;/a&gt;, the creator of literate programming. Knuth calls for a form of programming where we shift our focus from instructing the computer what to do, to explaining to another person what we &lt;i&gt;want&lt;/i&gt; the computer to do. This forms the basis for literate programming.&lt;/p&gt;&lt;p&gt;A literate source code file inverts the typical notion of a source code file: rather than being source code with comments strewn around, is a text with source code blocks inserted. The exact file format and medium of the file doesn&apos;t matter. The most well-known literate programming tool&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt; is probably &lt;a href=&quot;https://en.wikipedia.org/wiki/Project_Jupyter#Jupyter_Notebook&quot;&gt;Jupyter Notebook&lt;/a&gt;.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Org mode&lt;/h3&gt;&lt;p&gt;With Emacs, Org mode is arguably the most readily available way to do literate programming. &lt;a href=&quot;https://orgmode.org/worg/org-contrib/babel/&quot;&gt;Babel&lt;/a&gt;, which has been included in Org mode since version 7.0, enhances Org mode&apos;s source blocks by providing (as described in &lt;a href=&quot;https://orgmode.org/worg/org-contrib/babel/intro.html#introduction&quot;&gt;the introductory tutorial&lt;/a&gt;)&lt;/p&gt;&lt;ul&gt;&lt;li&gt;interactive and on-export execution of code blocks&lt;/li&gt;&lt;li&gt;code blocks as functions that can be parameterized, that can refer to other code blocks, and that can be called remotely&lt;/li&gt;&lt;li&gt;export to files for literate programming&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;In short, this enables you to write Org documents with source code blocks, where the source code blocks can be interacted with and used to generate pure source code.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Configuring Emacs&lt;/h2&gt;&lt;p&gt;It turns out that if you&apos;re on a semi-recent version of Emacs, it&apos;s really very simple. Babel provides a function called &lt;code&gt;org-babel-load-file&lt;/code&gt; which &apos;Load[s] Emacs Lisp source code blocks in the Org [file]&apos;. As such, all you need to do is to call this function from your Emacs configuration with the path to the Org file you want to load.&lt;/p&gt;&lt;p&gt;Here&apos;s what I&apos;ve got in my configuration:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-elisp&quot;&gt;(org-babel-load-file
 (expand-file-name
  &quot;config.org&quot;
  user-emacs-directory))&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This snippet assumes that the file you&apos;re loading is located in a file called &lt;code&gt;config.org&lt;/code&gt; in your &lt;code&gt;user-emacs-directory&lt;/code&gt; (which defaults to &lt;code&gt;~/.emacs.d&lt;/code&gt;).&lt;/p&gt;&lt;p&gt;This was tested with vanilla Emacs 26.3, so any recent version of Emacs shouldn&apos;t need any more configuration than this, but if you want a more detailed guide, check out the &lt;a href=&quot;https://orgmode.org/worg/org-contrib/babel/intro.html#emacs-initialization&quot;&gt;Emacs Initialization with Babel&lt;/a&gt; section of the Babel introduction.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Benefits of using Org mode for configuration&lt;/h2&gt;&lt;p&gt;So far, I&apos;ve found a number of benefits to using literate programming for my configuration, including (but not limited to):&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;I&apos;m able to express /why/ I&apos;m making certain configurations&lt;/dt&gt;&lt;dd&gt;Not that you &lt;i&gt;can&apos;t&lt;/i&gt; describe what you&apos;re doing or why in pure elisp, but I certainly find it harder to be clear about it. Explaining the reasoning behind making certain configuration decisions is not only useful to other people reading my configuration, but also to myself when I return to something after weeks or months (or years) after having last touched it. &apos;Why did I configure it this way again? Oh, yeah: that&apos;s it!&quot;&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;Furthermore, being able to use a text-based mode to write text not only makes a lot of sense, but it&apos;s also much more ergonomic, and offers much more expressibility than code comments.&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Formatting&lt;/dt&gt;&lt;dd&gt;Another bonus of using a text-based mode is that you can take advantage of text formatting. For instance, being able to include links that only display a link text and not a full URL is a nice bonus. Lists (numbered, unnumbered, and definition lists) are also readily available.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Expanding and collapsing regions&lt;/dt&gt;&lt;dd&gt;If you want to get a quick overview over your configuration, it&apos;s easy to quickly toggle the headings in the entire file to find exactly what you&apos;re looking for. It&apos;s also super easy to narrow your editor view to the section you&apos;re focusing on right now.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Using tags&lt;/dt&gt;&lt;dd&gt;Even better than being able to fold your config and scan through the headings is using tags. Org mode&apos;s support for tags makes it a breeze to show only sections that relate to whatever you&apos;re looking for. For instance: one of the tags I&apos;ve defined is &lt;code&gt;keybinding&lt;/code&gt;. By tagging every section that deals with key bindings with this, I can quickly whip up a view that shows all the relevant sections by using &lt;code&gt;org-sparse-tree&lt;/code&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Summary&lt;/h2&gt;&lt;p&gt;That sums up my journey into literate programming thus far. I still have a lot to learn and have probably only truly understood a fraction of the power that lies within Org mode, but I&apos;ve gotten over that first step. It&apos;s not (as) scary anymore, and I&apos;m looking forward to learning more about it.&lt;/p&gt;&lt;p&gt;If you came here looking for how to use Org mode to configure Emacs or to do literate programming, I hope you found what you were looking for. And if you came here wondering what this was all about, I hope your curiosity was rewarded and that you&apos;re still at least &lt;i&gt;as&lt;/i&gt; curious or intrigued as before.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Further reading and references&lt;/h2&gt;&lt;p&gt;I&apos;ve included a few links that could be useful or interesting below. Most of them are already linked to in the text above, but included here again for convenience.&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;[[https://en.wikipedia.org/wiki/Literate_programming][Wikipedia on Literate programming]]&lt;/dt&gt;&lt;dd&gt;As per usual, Wikipedia offers a concise and informative take on what literate programming is and where it comes from. In addition to the basics, it also includes a very nice illustration of literate programming by showing certain parts of the Unix word count utility &lt;code&gt;wc&lt;/code&gt; written using literate programming techniques.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;[[http://www.literateprogramming.com][literateprogramming.com]]&lt;/dt&gt;&lt;dd&gt;A website about literate programming. There&apos;s not much information about the purpose of the website, nothing to be found about the author, and it looks like it hasn&apos;t been updated since 2009, but there are some resource links, and a great many quotes about literate programming and how programs tend to be underdocumented.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;[[https://orgmode.org/worg/org-contrib/babel/][Babel: active code in Org-mode]]&lt;/dt&gt;&lt;dd&gt;This website includes links the Babel reference documentation, the introductory tutorial, a journal paper describing the use of Org mode and Babel for literate programming and reproducible research, and more.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;[[https://github.com/thomasheartman/.emacs.d/blob/develop/config.org][My literate Emacs config]]&lt;/dt&gt;&lt;dd&gt;This is the config I use at the time of writing. Note that it is not my complete Emacs configuration, but rather an addition to my main configuration. I&apos;m in the process of (very slowly) moving away from Spacemacs and into my own configuration, so this document reflects that.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;/div&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;Or at least the only one that I hear mentioned at semi-regular intervals.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dl id=&quot;footnotes&quot;&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;Or at least the only one that I hear mentioned at semi-regular intervals.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;/dl&gt;</content:encoded></item><item><title><![CDATA[Building a request inspector]]></title><description><![CDATA[In which I tell the story about how I barely managed to scrape together single-endpoint server in Rust. Far from a tutorial, this is more akin to a snapshot of how I've spent my weekend and a document to how I put things together when I don't know what I'm doing.]]></description><link>https://blog.thomasheartman.com/posts/building-a-request-inspector</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/building-a-request-inspector</guid><pubDate>Mon, 20 Apr 2020 17:32:32 GMT</pubDate><content:encoded>&lt;p&gt;I&apos;ve been quite involved with distributed tracing and have spent a fair amount of time looking at the &lt;a href=&quot;https://www.w3.org/TR/trace-context/&quot;&gt;W3C recommendation for dealing with trace context&lt;/a&gt; at work lately. As a result of this, I have found myself wanting to inspect the headers on outbound requests to ensure that the framework and libraries we use handle tracing correctly.&lt;/p&gt;&lt;p&gt;But how do you do that? I couldn&apos;t find any services or command line utilities that did this (at least not simply), so I set out to build one myself. It&apos;s been a while since I did anything in Rust, and this sounded like a fun, little weekend project. &lt;strong&gt;Spoiler alert:&lt;/strong&gt; It wasn&apos;t.&lt;/p&gt;&lt;p&gt;I wanted this to be a short and simple tutorial on how to build such a server in Rust, but things didn&apos;t go quite as I planned, and it took much more time and effort than I expected. Rather than hiding it and pretending it never happened, though, I&apos;m going to take it and run with it. I&apos;m sure that if I&apos;m running into these issues, I&apos;m not the only one.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Intended audience&lt;/h2&gt;&lt;p&gt;This post is intended for people who have at least &lt;i&gt;some&lt;/i&gt; experience with Rust, including familiarity with the type system and the borrow checker (at least as concepts). You should also have some passing knowledge of HTTP requests.&lt;/p&gt;&lt;p&gt;This post is &lt;i&gt;not&lt;/i&gt; intended to be a thorough tutorial or a list of best practices, but rather to serve as a way of demonstrate how I work. Yes, the code here works and runs as expected, and clippy doesn&apos;t complain, but it&apos;s not &lt;i&gt;good&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;There are code samples below, and you can also &lt;a href=&quot;https://gitlab.com/thomasheartman/reqspec&quot;&gt;check out the repo on GitLab&lt;/a&gt;. However, this should not be considered a final version, and there will likely be further updates to the repo later on. This is also not an in-depth analysis of the code, but a short tour of it. In short: it works, but it&apos;s far from perfect. In a lot of ways, writing this code felt a lot like how &lt;a href=&quot;https://theoatmeal.com/&quot;&gt;the Oatmeal&lt;/a&gt; describes projects coming together in his fantastic comic &lt;a href=&quot;https://theoatmeal.com/comics/creativity_erasers&quot;&gt;&apos;Erasers are Wonderful&apos;&lt;/a&gt;: full of twists, turns, and toilet fires, and in the end you have something that&apos;s &lt;i&gt;good enough&lt;/i&gt;.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The goal&lt;/h2&gt;&lt;p&gt;I set out to make a simple web server that:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;would accept requests at any endpoint&lt;/li&gt;&lt;li&gt;would accept requests with any method&lt;/li&gt;&lt;li&gt;would respond with a JSON object containing data about the request&apos;s:&lt;/li&gt;&lt;ul&gt;&lt;li&gt;headers&lt;/li&gt;&lt;li&gt;method&lt;/li&gt;&lt;li&gt;path&lt;/li&gt;&lt;li&gt;query string&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;p&gt;I also wanted to add the request body (if there was one) to the response, but it wasn&apos;t the most important issue. Other additional features, such as reading data from environment variables, command line options, logging, etc., could be added later.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;How (or: &apos;show me the code&apos;)&lt;/h2&gt;&lt;p&gt;When building a web server in Rust, there&apos;s a number of frameworks to choose from. I first went with &lt;a href=&quot;https://actix.rs/&quot;&gt;Actix&lt;/a&gt;, but after &lt;i&gt;not&lt;/i&gt; reading the docs, ended up working directly with &lt;a href=&quot;https://hyper.rs/&quot;&gt;Hyper&lt;/a&gt; because it was easier to create a function that would handle any request at any route with any method. Or at least it was covered in the initial tutorial.&lt;/p&gt;&lt;p&gt;In addition to Hyper, I&apos;m also pulling in &lt;a href=&quot;https://docs.rs/anyhow/1.0.28/anyhow/index.html&quot;&gt;anyhow&lt;/a&gt; and &lt;a href=&quot;https://github.com/serde-rs/json&quot;&gt;serde-json&lt;/a&gt; for dealing with errors and working with JSON.&lt;/p&gt;&lt;p&gt;Below, we&apos;ll break the program up into functions and look at them one at a time.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Dependencies and imports&lt;/h3&gt;&lt;p&gt;Let&apos;s get the boring (but very important) bits out of the way. Here&apos;s the &lt;code&gt;dependencies&lt;/code&gt; section of the &lt;code&gt;Cargo.toml&lt;/code&gt; file, as well as the program imports.&lt;/p&gt;&lt;p&gt;Dependencies:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-toml&quot;&gt;&lt;span class=&quot;hljs-section&quot;&gt;[dependencies]&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;hyper&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;0.13&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;tokio&lt;/span&gt; = { version = &lt;span class=&quot;hljs-string&quot;&gt;&quot;0.2&quot;&lt;/span&gt;, features = [&lt;span class=&quot;hljs-string&quot;&gt;&quot;full&quot;&lt;/span&gt;] }
&lt;span class=&quot;hljs-attr&quot;&gt;serde_json&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;1.0&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;anyhow&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;1.0&quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Imports:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;use&lt;/span&gt; anyhow::&lt;span class=&quot;hljs-built_in&quot;&gt;Result&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;use&lt;/span&gt; hyper::service::{make_service_fn, service_fn};
&lt;span class=&quot;hljs-keyword&quot;&gt;use&lt;/span&gt; hyper::{Body, HeaderMap, Request, Response, Server};
&lt;span class=&quot;hljs-keyword&quot;&gt;use&lt;/span&gt; serde_json::json;
&lt;span class=&quot;hljs-keyword&quot;&gt;use&lt;/span&gt; std::collections::HashMap;
&lt;span class=&quot;hljs-keyword&quot;&gt;use&lt;/span&gt; std::convert::Infallible;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;The &lt;code&gt;main&lt;/code&gt; function&lt;/h3&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-meta&quot;&gt;#[tokio::main]&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() -&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;Result&lt;/span&gt;&amp;#x3C;(), hyper::error::Error&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; make_svc = make_service_fn(|_| &lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; { Ok::&amp;#x3C;_, Infallible&gt;(service_fn(handle_requests)) });

    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; addr = ([&lt;span class=&quot;hljs-number&quot;&gt;127&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;], &lt;span class=&quot;hljs-number&quot;&gt;8080&lt;/span&gt;).into();

    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; server = Server::bind(&amp;#x26;addr).serve(make_svc);

    &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;Server started. Listening on http://{}&quot;&lt;/span&gt;, addr);

    server.&lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;There&apos;s a few things happening here, but it&apos;s rather self-explanatory. We declare a handler and an address for the server; start the server with the aforementioned handler and address, and wait for it to finish (which happens on termination).&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;The request handler&lt;/h3&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;handle_requests&lt;/span&gt;&lt;/span&gt;(req: Request&amp;#x3C;Body&gt;) -&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;Result&lt;/span&gt;&amp;#x3C;Response&amp;#x3C;Body&gt;&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; response_data = json!({
        &lt;span class=&quot;hljs-string&quot;&gt;&quot;headers&quot;&lt;/span&gt;: to_string_map(req.headers()),
        &lt;span class=&quot;hljs-string&quot;&gt;&quot;path&quot;&lt;/span&gt;: req.uri().path(),
        &lt;span class=&quot;hljs-string&quot;&gt;&quot;queryString&quot;&lt;/span&gt;: req.uri().query(),
        &lt;span class=&quot;hljs-string&quot;&gt;&quot;method&quot;&lt;/span&gt;: req.method().as_str(),
        &lt;span class=&quot;hljs-string&quot;&gt;&quot;version&quot;&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;format!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;{:?}&quot;&lt;/span&gt;, req.version()),
    }).to_string();

    &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;Received request: {:?}&quot;&lt;/span&gt;, response_data);

    &lt;span class=&quot;hljs-literal&quot;&gt;Ok&lt;/span&gt;(Response::builder()
       .header(&lt;span class=&quot;hljs-string&quot;&gt;&quot;content-type&quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&quot;application/json&quot;&lt;/span&gt;)
       .body(Body::from(response_data))?)
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This is the meat of the program and really what it&apos;s all about: extracting data from the request and returning it to the caller. As this is a very rough proof of concept, I&apos;m mapping the the data into a completely arbitrary JSON structure rather than into a struct.&lt;/p&gt;&lt;p&gt;After mapping, I print the result of the mapping, and return the response with an appropriate content-type.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Serializing the &lt;code&gt;HeaderMap&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;Serde takes care of serializing most of the data very well, but doesn&apos;t like the &lt;code&gt;HeaderMap&lt;/code&gt; which contains the request&apos;s headers. &lt;a href=&quot;https://docs.rs/hyper/0.13.5/hyper/struct.HeaderMap.html&quot;&gt;~HeaderMap~&lt;/a&gt; is a &lt;i&gt;multimap&lt;/i&gt;---a map structure that can associate multiple values with a single key---and as such, doesn&apos;t easily serialize to JSON.&lt;/p&gt;&lt;p&gt;To solve this, I decided to turn the &lt;code&gt;HeaderMap&lt;/code&gt; into a &lt;code&gt;HashMap&amp;#x3C;String, String&gt;&lt;/code&gt;, simply creating a comma-separated string for headers that have multiple values. Not the most elegant or robust solution, but hey, it works.&lt;/p&gt;&lt;p&gt;Also, because the &lt;code&gt;header_value.to_str&lt;/code&gt; function &apos;yields a &amp;#x26;str slice if the HeaderValue only contains visible ASCII chars&apos; (according to &lt;a href=&quot;https://docs.rs/hyper/0.13.5/hyper/header/struct.HeaderValue.html#method.to_str&quot;&gt;the docs&lt;/a&gt;), I put ~&quot;Non-ASCII header value&quot;~  to handle cases where it contains non-ASCII characters.. Again: &lt;i&gt;it works&lt;/i&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;to_string_map&lt;/span&gt;&lt;/span&gt;(headers: &amp;#x26;HeaderMap) -&gt; HashMap&amp;#x3C;&lt;span class=&quot;hljs-built_in&quot;&gt;String&lt;/span&gt;, &lt;span class=&quot;hljs-built_in&quot;&gt;String&lt;/span&gt;&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;mut&lt;/span&gt; map = HashMap::new();
    &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; (header_name, header_value) &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; headers.iter() {
        &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; k = header_name.as_str();
        &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; v = header_value
            .to_str()
            .unwrap_or(&lt;span class=&quot;hljs-string&quot;&gt;&quot;Non-ASCII header value&quot;&lt;/span&gt;)
            .into();

        &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; map.get_mut(k) {
            &lt;span class=&quot;hljs-literal&quot;&gt;None&lt;/span&gt; =&gt; {
                map.insert(k.into(), v);
            }
            &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(old_val) =&gt; *old_val = &lt;span class=&quot;hljs-built_in&quot;&gt;format!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;{}, {}&quot;&lt;/span&gt;, old_val, v),
        }
    }

    map
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The unexpected challenges&lt;/h2&gt;&lt;p&gt;So what made this so difficult? Why didn&apos;t it work out as I expected? Well, here&apos;s some of the issues I ran into:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;The request body&lt;/dt&gt;&lt;dd&gt;As briefly mentioned up top, I originally wanted to also include the request body in the response. I spent too much time on trying to make this work before realizing that I should leave it out for now.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;This turned out to be difficult because of how I couldn&apos;t easily parse the body as a &lt;code&gt;String&lt;/code&gt; and include that in the output JSON. But after a bit of thought, I realized that I can&apos;t just assume that the body is JSON (or even a string), so it&apos;s more work than I expected.&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Converting between different types&lt;/dt&gt;&lt;dd&gt;Related to the issues with the request body is conversion between different data types, and especially between types that are and aren&apos;t serializable by Serde. It felt like there was a lot of juggling types around just to please the compiler.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Manually serializing data types&lt;/dt&gt;&lt;dd&gt;While most of the data types can easily be represented as strings in this case, the header map needed some work. While it wasn&apos;t a very difficult exercise, it took more time than expected, especially because there wasn&apos;t an obvious way to perform an &lt;i&gt;upsert&lt;/i&gt;-like action into a &lt;code&gt;HashMap&lt;/code&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Lack of examples&lt;/dt&gt;&lt;dd&gt;This could be me or it could be the documentation, but I found it difficult to do what I wanted. I&apos;d expected there to be more information on getting data from a request, but it&apos;s quite possible that I just didn&apos;t read far enough.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;I&apos;m ... /rusty/&lt;/dt&gt;&lt;dd&gt;It&apos;s been a while since I last worked with Rust, and the borrow-checker was stricter than I remember.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Working directly with Hyper?&lt;/dt&gt;&lt;dd&gt;I don&apos;t know whether this was much of an issue or not. It gave me quick and easy access to the endpoint setup I wanted, but it might have introduced other complications. That said, it looks as if Actix simply re-exports a lot of Hyper&apos;s data types, so I don&apos;t know how much of a difference that would have made.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Wrapping up&lt;/h2&gt;&lt;p&gt;Even if things didn&apos;t go exactly as planned, it was a fun, and at times very frustrating, little project. Having looked a little bit more at the Actix docs, I have found a few sections that make me think it could be quite suitable after all, so I&apos;ll probably rewrite the project some fourteen times in the coming week.&lt;/p&gt;&lt;p&gt;Next time I&apos;ll hopefully have something a bit more polished to show off.&lt;/p&gt;&lt;p&gt;Peace.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[On null and undefined]]></title><description><![CDATA[Some thoughts on the difference between `null` and `undefined` in JavaScript and in JSON, and how that impacts their use. Also briefly discusses how this split is (or isn't) handled by a lot of server side languages that don't have the distinction between `null` and `undefined`.]]></description><link>https://blog.thomasheartman.com/posts/on-null-and-undefined</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/on-null-and-undefined</guid><pubDate>Mon, 13 Apr 2020 14:53:21 GMT</pubDate><content:encoded>&lt;p&gt;I came across a tweet the other day (no link, sorry), where the author said they&apos;d stopped using &lt;code&gt;null&lt;/code&gt; in JavaScript, instead using only &lt;code&gt;undefined&lt;/code&gt;. The author was encouraging the readers to do the same. From what I can remember, the reason for this was that mixing &lt;code&gt;null&lt;/code&gt; and &lt;code&gt;undefined&lt;/code&gt; can be confusing and lead to weird bugs in your application.&lt;/p&gt;&lt;p&gt;I&apos;ve also heard a number of dev friends express negative emotions towards the fact that JavaScript has both &lt;code&gt;null&lt;/code&gt; and &lt;code&gt;undefined&lt;/code&gt;, saying it makes things harder.&lt;/p&gt;&lt;p&gt;However, I&apos;m in the camp where I think having both &lt;code&gt;null&lt;/code&gt; &lt;i&gt;and&lt;/i&gt; &lt;code&gt;undefined&lt;/code&gt; is a good thing because they are separate concepts. In this post, I want to discuss and put forward the way I view them, both in JavaScript itself, and also as part of a JSON API.&lt;/p&gt;&lt;p&gt;Note: this is largely my own opinion, and I do not have a significant amount of literature to back it up. I welcome opinions and discussions on this!&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;JavaScript&lt;/h2&gt;&lt;p&gt;In JavaScript, both &lt;code&gt;null&lt;/code&gt; and &lt;code&gt;undefined&lt;/code&gt; represent an absence of value. However, the kind of absence they represent is quite different from one another.&lt;/p&gt;&lt;p&gt;&lt;code&gt;undefined&lt;/code&gt; values are values that have simply not been defined. &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Glossary/undefined&quot;&gt;MDN says&lt;/a&gt; that &apos;&lt;code&gt;undefined&lt;/code&gt; is a primitive value automatically assigned to variables that have just been declared, or to formal arguments for which there are no actual arguments.&apos;:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-javascript&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; x &lt;span class=&quot;hljs-comment&quot;&gt;// x is `undefined`&lt;/span&gt;

&lt;span class=&quot;hljs-keyword&quot;&gt;var&lt;/span&gt; y &lt;span class=&quot;hljs-comment&quot;&gt;// y is `undefined`&lt;/span&gt;

&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; f = &lt;span class=&quot;hljs-function&quot;&gt;(&lt;span class=&quot;hljs-params&quot;&gt;x&lt;/span&gt;) =&gt;&lt;/span&gt;
  &lt;span class=&quot;hljs-built_in&quot;&gt;console&lt;/span&gt;.log(&lt;span class=&quot;hljs-string&quot;&gt;&apos;x is&apos;&lt;/span&gt;, x)

f() &lt;span class=&quot;hljs-comment&quot;&gt;// prints &apos;x is undefined&apos;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Additionally, the return value of a function that doesn&apos;t return anything is &lt;code&gt;undefined&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-javascript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// returns `undefined`&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; g = &lt;span class=&quot;hljs-function&quot;&gt;() =&gt;&lt;/span&gt; {}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;On the other hand, &lt;code&gt;null&lt;/code&gt; is never implicitly assigned. It must always be assigned &lt;i&gt;explicitly&lt;/i&gt; by the programmer. This makes &lt;code&gt;null&lt;/code&gt; well suited for cases when you want to represent a value that can either be present or not, similar to Haskell&apos;s &lt;code&gt;Maybe&lt;/code&gt; and Rust&apos;s &lt;code&gt;Option&lt;/code&gt;.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;In short&lt;/h3&gt;&lt;p&gt;An &lt;code&gt;undefined&lt;/code&gt; value is something that hasn&apos;t been assigned, while a &lt;code&gt;null&lt;/code&gt; value has been assigned that specific value.&lt;/p&gt;&lt;p&gt;Does that matter in your application code? I&apos;m inclined to think that it&apos;s not much of a big deal whether you use only one or both. In my experience, most cases will be testing the &apos;truthiness&apos; of a value anyway, so &lt;code&gt;null&lt;/code&gt; and &lt;code&gt;undefined&lt;/code&gt; can intermingle freely.&lt;/p&gt;&lt;p&gt;Where it does matter, though, is in areas where these two concepts carry different meanings, such as when communicating via JSON, which is what we&apos;ll be looking at in the next section.&lt;/p&gt;&lt;p&gt;Personally, I&apos;m &apos;Team Both&apos;. I&apos;ll use &lt;code&gt;undefined&lt;/code&gt; for optional parameters to React components or optional keys of object arguments that I expect, and I&apos;ll set a value to &lt;code&gt;null&lt;/code&gt; if I intend it to carry a semantic meaning.&lt;/p&gt;&lt;p&gt;What do I think you should do? Whatever fits your use case. If you have no need to differentiate between these two, then it really doesn&apos;t matter much what you do. If you&apos;d prefer to only use the one, that&apos;s perfectly fine by me.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;JSON and APIs&lt;/h2&gt;&lt;p&gt;While &lt;code&gt;null&lt;/code&gt; and &lt;code&gt;undefined&lt;/code&gt; may carry largely the same meaning in JavaScript, they have quite distinct meanings in JSON&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt; and when communicating with an API. This is especially true when making PATCH requests.&lt;/p&gt;&lt;p&gt;The &lt;a href=&quot;https://tools.ietf.org/html/rfc7396&quot;&gt;RFC for the JSON Merge Patch document format (7396)&lt;/a&gt; states that when patching, an &lt;code&gt;undefined&lt;/code&gt; value should be left as is and a &lt;code&gt;null&lt;/code&gt; value should be removed. This means that the two values have wildly different meanings and that mixing them up can cause some very unwanted side effects.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;The API story&lt;/h3&gt;&lt;p&gt;However, even if JSON works as described above and JavaScript has both &lt;code&gt;undefined&lt;/code&gt; and &lt;code&gt;null&lt;/code&gt;, a lot of server-side languages don&apos;t have this distinction. And they&apos;re also often statically typed languages that need to populate a model. This can lead to problems.&lt;/p&gt;&lt;p&gt;Where I work, most of the backend systems are written in C#, where we must have defined classes for JSON payloads. C# doesn&apos;t have &lt;code&gt;undefined&lt;/code&gt;, so depending on how you configure your system, it can either mark non-existing fields as &lt;code&gt;null&lt;/code&gt; or throw an error because it didn&apos;t get all the data it needed. When you&apos;re working with PATCH as described above, neither of those are ideal.&lt;/p&gt;&lt;p&gt;I don&apos;t know of any libraries (in any statically typed languages) that have an elegant solution for this, but I&apos;d be very interested in hearing about it if you do. It may not be applicable to any languages I work with, but just seeing a solution would be very interesting.&lt;/p&gt;&lt;hr&gt;&lt;p&gt;So those are my thoughts. I think there is a clear difference between &lt;code&gt;null&lt;/code&gt; and &lt;code&gt;undefined&lt;/code&gt;, and I support having both. In some cases, they might be interchangeable, but if nothing else, I maintain that they express intent differently, so I think it&apos;s worth it just for that.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;/div&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;To be clear: JSON doesn&apos;t have an explicit &lt;code&gt;undefined&lt;/code&gt; value, but you can leave out a field, which serves the same purpose:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-javascript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// JS object&lt;/span&gt;
{
  &lt;span class=&quot;hljs-attr&quot;&gt;a&lt;/span&gt;: &lt;span class=&quot;hljs-literal&quot;&gt;null&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;b&lt;/span&gt;: &lt;span class=&quot;hljs-literal&quot;&gt;undefined&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;c&lt;/span&gt;: &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;
}

&lt;span class=&quot;hljs-comment&quot;&gt;// JSON object, converted&lt;/span&gt;
{
  &lt;span class=&quot;hljs-string&quot;&gt;&quot;a&quot;&lt;/span&gt;: &lt;span class=&quot;hljs-literal&quot;&gt;null&lt;/span&gt;,
  &lt;span class=&quot;hljs-string&quot;&gt;&quot;c&quot;&lt;/span&gt;: &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dl id=&quot;footnotes&quot;&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;To be clear: JSON doesn&apos;t have an explicit &lt;code&gt;undefined&lt;/code&gt; value, but you can leave out a field, which serves the same purpose:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-javascript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// JS object&lt;/span&gt;
{
  &lt;span class=&quot;hljs-attr&quot;&gt;a&lt;/span&gt;: &lt;span class=&quot;hljs-literal&quot;&gt;null&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;b&lt;/span&gt;: &lt;span class=&quot;hljs-literal&quot;&gt;undefined&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;c&lt;/span&gt;: &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;
}

&lt;span class=&quot;hljs-comment&quot;&gt;// JSON object, converted&lt;/span&gt;
{
  &lt;span class=&quot;hljs-string&quot;&gt;&quot;a&quot;&lt;/span&gt;: &lt;span class=&quot;hljs-literal&quot;&gt;null&lt;/span&gt;,
  &lt;span class=&quot;hljs-string&quot;&gt;&quot;c&quot;&lt;/span&gt;: &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/dd&gt;&lt;/dl&gt;</content:encoded></item><item><title><![CDATA[Haskell's Maybe and Either types]]></title><description><![CDATA[In which we have an introductory glance at the Maybe and Either types in Haskell. An unusual entry in the series of reading Haskell Programming from First Principles, but an entry nonetheless.]]></description><link>https://blog.thomasheartman.com/posts/haskells-maybe-and-either-types</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/haskells-maybe-and-either-types</guid><pubDate>Mon, 06 Apr 2020 08:23:42 GMT</pubDate><content:encoded>&lt;p&gt;If you don&apos;t have exceptions and you don&apos;t have &lt;code&gt;null&lt;/code&gt;: How do you handle errors and invalid inputs? Based on your background, this can either be trivial or mind-bending. Coming into the Haskell (actually: Elm and Rust) world from C#, JavaScript, and Python, it definitely wasn&apos;t obvious to me at first.&lt;/p&gt;&lt;p&gt;Luckily, the &lt;code&gt;Maybe&lt;/code&gt; and &lt;code&gt;Either&lt;/code&gt; types are there for you, and they are fairly easy to get started with. In this post, I want to give a quick introduction to both of these data types and how they&apos;re used.&lt;/p&gt;&lt;pre class=&quot;aside&quot;&gt;To any returning readers: This post is based chapter 12 of /Haskell Programming
from First Principles/, which deals with basic error handling in Haskell, using
the ~Maybe~ and ~Either~ types. The chapter doesn&apos;t actually introduce much else
of interest, so I wanted to approach this entry slightly differently.&lt;/pre&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;What we will (and won&apos;t) be covering&lt;/h2&gt;&lt;p&gt;This post is intended to be a brief introduction to the &lt;code&gt;Maybe&lt;/code&gt; and &lt;code&gt;Either&lt;/code&gt; data types in Haskell; suitable for someone who has no previous experience with these. Some understanding of Haskell syntax would be beneficial, but is not required. The post should give the reader a basic understanding of what &lt;code&gt;Maybe&lt;/code&gt; and &lt;code&gt;Either&lt;/code&gt; are and how they can be used for modeling data and responses.&lt;/p&gt;&lt;p&gt;This post is &lt;i&gt;not&lt;/i&gt; intended to be a thorough examination of these types. It will not discuss anything related to typeclasses, mapping, or binding. There will also not be any extensive code samples. As such, please note that there is a lot more to these data types than we will look at here, but that most of it is out of scope for this post.&lt;/p&gt;&lt;p&gt;For further reading, please consult the section at the end of the article.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;&lt;code&gt;Maybe&lt;/code&gt;&lt;/h2&gt;&lt;p&gt;&lt;code&gt;Maybe&lt;/code&gt; represents the potential absence of a value. It is used when some data can be in one of two states: defined/present, or undefined/absent. Because &lt;code&gt;Maybe&lt;/code&gt; represents a value that may or may not be present, we also need to specify the type of the potentially contained item: &lt;code&gt;Maybe String&lt;/code&gt;, &lt;code&gt;Maybe Integer&lt;/code&gt;, or &lt;code&gt;Maybe a&lt;/code&gt; for instance.&lt;/p&gt;&lt;p&gt;In many ways, &lt;code&gt;Maybe&lt;/code&gt; is similar to &lt;code&gt;null&lt;/code&gt; in C#, JavaScript, etc., &lt;code&gt;None&lt;/code&gt; in Python, and related concepts (like &lt;code&gt;nil&lt;/code&gt;) in a lot of other languages. However, in these other languages, the potential lack of a value is (almost) always implicit, meaning the programmer can never be sure whether the value is there or not. In Haskell, this is always explicit. The &lt;code&gt;Maybe&lt;/code&gt; type is the same as the &lt;code&gt;Option&lt;/code&gt; type in languages like Rust and F#.&lt;/p&gt;&lt;p&gt;The data declaration looks a little something like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Maybe&lt;/span&gt; a = &lt;span class=&quot;hljs-type&quot;&gt;Nothing&lt;/span&gt; | &lt;span class=&quot;hljs-type&quot;&gt;Just&lt;/span&gt; a&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As such, &lt;code&gt;Maybe&lt;/code&gt; has two data constructors, &lt;code&gt;Nothing&lt;/code&gt; and &lt;code&gt;Just&lt;/code&gt;, where the latter takes a value to wrap.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Basic usage&lt;/h3&gt;&lt;p&gt;While there&apos;s any number of ways you can use the &lt;code&gt;Maybe&lt;/code&gt; type in your programs, I find the two most obvious ways to be&lt;/p&gt;&lt;ol&gt;&lt;li&gt;to model data where some parts are optional&lt;/li&gt;&lt;li&gt;to return something from a function if the input is invalid&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;Being able to indicate that a value may or may not be present is a simple, but very powerful tool of modeling data. Imagine you&apos;ve created a dating app for Haskellers---let&apos;s call it &lt;i&gt;Hinder&lt;/i&gt;---where you want to display a list of users. The list should display only their profile picture and their name, but there&apos;s no requirement to have set a profile picture to be listed, so we&apos;ll need to account for that. A simplistic way to model that would be by using a list of records like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;User&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;User&lt;/span&gt;&lt;/span&gt;
  { name :: &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt;
  , picture :: &lt;span class=&quot;hljs-type&quot;&gt;Maybe&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt;
  }&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Where the &lt;code&gt;picture&lt;/code&gt; value is &lt;code&gt;Nothing&lt;/code&gt; if there is no profile picture set. If they have a profile picture, it&apos;s &lt;code&gt;Just &amp;#x3C;picture id&gt;&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;The other way to use &lt;code&gt;Maybe&lt;/code&gt; is as the return value of a function. As much as possible, you should use the type system to constrain the set of allowed arguments to a function, but that&apos;ll only get you so far. The built-in &lt;code&gt;div&lt;/code&gt; function throws an exception if you pass &lt;code&gt;0&lt;/code&gt; as the second argument, so let&apos;s fix that by using &lt;code&gt;Maybe&lt;/code&gt;. If the divisor is &lt;code&gt;0&lt;/code&gt;, return &lt;code&gt;Nothing&lt;/code&gt;. Otherwise, return &lt;code&gt;Just &amp;#x3C;result&gt;&lt;/code&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;safeDiv&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;Integral&lt;/span&gt; a =&gt; a -&gt; a -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Maybe&lt;/span&gt; a
&lt;span class=&quot;hljs-title&quot;&gt;safeDiv&lt;/span&gt; _ &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;Nothing&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;safeDiv&lt;/span&gt; x y = &lt;span class=&quot;hljs-type&quot;&gt;Just&lt;/span&gt; $ x `div` y&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;&lt;code&gt;Either&lt;/code&gt;&lt;/h2&gt;&lt;p&gt;The &lt;code&gt;Either&lt;/code&gt; type is similar to the &lt;code&gt;Maybe&lt;/code&gt; type, but comes with some added functionality. It&apos;s also used to model things that can fail, but it provides a way to report &lt;i&gt;what&lt;/i&gt; went wrong, not just that &lt;i&gt;something&lt;/i&gt; failed.&lt;/p&gt;&lt;p&gt;&lt;code&gt;Either&lt;/code&gt; represents a piece of data that can be one of two things. That is, it can be &lt;i&gt;either&lt;/i&gt; &apos;this&apos; &lt;strong&gt;or&lt;/strong&gt; &apos;that&apos;, whatever &apos;this&apos; and &apos;that&apos; may be. &lt;code&gt;Either&lt;/code&gt; is parameterized by two types (so &apos;this&apos; and &apos;that&apos; can be of different types), meaning you&apos;ll usually see &lt;code&gt;Either a b&lt;/code&gt; or something like &lt;code&gt;Either String Int&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;Where &lt;code&gt;Maybe&lt;/code&gt; has a very easy analog in the concept of a &lt;code&gt;null&lt;/code&gt; value, &lt;code&gt;Either&lt;/code&gt; doesn&apos;t enjoy the same luxury. However, it is conceptually equivalent to the &lt;code&gt;Result&lt;/code&gt; type in Rust and F#, even if the order of the arguments are flipped.&lt;/p&gt;&lt;p&gt;The data declaration (simplified) looks like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Either&lt;/span&gt; a b = &lt;span class=&quot;hljs-type&quot;&gt;Left&lt;/span&gt; a | &lt;span class=&quot;hljs-type&quot;&gt;Right&lt;/span&gt; b&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;code&gt;Either&lt;/code&gt; has two data constructors, &lt;code&gt;Left&lt;/code&gt; and &lt;code&gt;Right&lt;/code&gt;, each of which take a single value. By convention, the &lt;code&gt;Left&lt;/code&gt; value is used for when something goes wrong, and the &lt;code&gt;Right&lt;/code&gt; value for when something goes, well, right.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Basic usage&lt;/h3&gt;&lt;p&gt;&lt;code&gt;Either&lt;/code&gt; is usually used for error handling and validation, so it&apos;s ideal as a return type of functions that can &apos;fail&apos; or that are otherwise not able to create a valid result based on the arguments given.&lt;/p&gt;&lt;p&gt;Let&apos;s return to our &lt;code&gt;safeDiv&lt;/code&gt; function from before. This time, however, we&apos;ll return an error message instead of &lt;code&gt;Nothing&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;safeDiv&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;Integral&lt;/span&gt; a =&gt; a -&gt; a -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Either&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt; a
&lt;span class=&quot;hljs-title&quot;&gt;safeDiv&lt;/span&gt; _ &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;Left&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&quot;You cannot divide by zero.&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;safeDiv&lt;/span&gt; x y = &lt;span class=&quot;hljs-type&quot;&gt;Right&lt;/span&gt; $ x `div` y&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The error may be obvious in this case, but for more complex functions (or chains of them), it gets ever more useful.&lt;/p&gt;&lt;p&gt;For a slightly more advanced example, imagine you&apos;re creating a &lt;code&gt;Person&lt;/code&gt; record. In this case, a &lt;code&gt;Person&lt;/code&gt; has a name of type &lt;code&gt;String&lt;/code&gt; and an &lt;code&gt;Age&lt;/code&gt; of type &lt;code&gt;Integer&lt;/code&gt;. But with these constraints, we can easily pass in invalid values, so we&apos;ll have to validate that the name isn&apos;t an empty string and that the age is non-negative:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;PersonError&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;InvalidName&lt;/span&gt; | &lt;span class=&quot;hljs-type&quot;&gt;InvalidAge&lt;/span&gt;&lt;/span&gt;

&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Person&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;Person&lt;/span&gt;&lt;/span&gt;
  { name :: &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt;
  , age :: &lt;span class=&quot;hljs-type&quot;&gt;Integer&lt;/span&gt;
  }

&lt;span class=&quot;hljs-title&quot;&gt;makePerson&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Integer&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Either&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;PersonError&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Person&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;makePerson&lt;/span&gt; name age = undefined &lt;span class=&quot;hljs-comment&quot;&gt;-- exercise for the reader ;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The actual implementation of the validation isn&apos;t important in this case, so I&apos;ve left that as an exercise for the reader. Oh, and what if there are multiple errors? Well, we can deal with that too, but that&apos;s not for now.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Further reading&lt;/h2&gt;&lt;p&gt;If you have found the article useful and would like to learn more about &lt;code&gt;Maybe&lt;/code&gt;, &lt;code&gt;Either&lt;/code&gt;, and error handling, here&apos;s a little list of useful resources:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;The [[https://wiki.haskell.org/][Haskell Wiki]]&lt;/dt&gt;&lt;dd&gt;The Haskell wiki is usually one of the first places I&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;check when I want more information on anything Haskell. They have an [[https://wiki.haskell.org/Maybe][article on Maybe]] as well as one on &lt;a href=&quot;https://wiki.haskell.org/Handling_errors_in_Haskell&quot;&gt;error handling&lt;/a&gt;, which has sections on both &lt;a href=&quot;https://wiki.haskell.org/Handling_errors_in_Haskell#No_value_using_the_Maybe_type&quot;&gt;~Maybe~&lt;/a&gt; and &lt;a href=&quot;https://wiki.haskell.org/Handling_errors_in_Haskell#Error_using_the_Either_type&quot;&gt;~Either~&lt;/a&gt;.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;http://learnyouahaskell.com/a-fistful-of-monads&quot;&gt;Learn You a Haskell&apos;s chapter /A Fistful of Monads/&lt;/a&gt; and &lt;a href=&quot;http://learnyouahaskell.com/a-fistful-of-monads#getting-our-feet-wet-with-maybe&quot;&gt;the section on ~Maybe~&lt;/a&gt; ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;a href=&quot;http://learnyouahaskell.com/&quot;&gt;Learn You a Haskell&lt;/a&gt; is a pretty good introduction to Haskell that&apos;s available in its entirety from the website. The content in the &lt;i&gt;Fistful of Monads&lt;/i&gt; chapter is a bit more advanced and might require reading some of the previous chapters, but both the chapter and the book could be well worth a look.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;The &lt;a href=&quot;https://www.schoolofhaskell.com/&quot;&gt;School of Haskell&lt;/a&gt; and the chapter on &lt;a href=&quot;https://www.schoolofhaskell.com/school/starting-with-haskell/basics-of-haskell/10_Error_Handling&quot;&gt;error handling&lt;/a&gt; ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;While I&apos;ve not used The School of Haskell as a resource myself, I did find the error handling chapter to be well written. Oh, and it&apos;s written by &lt;a href=&quot;https://bartoszmilewski.com/&quot;&gt;Bartosz Milewski&lt;/a&gt; so you can expect some interesting insights.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[On Generics and Associated Types]]></title><description><![CDATA[In which we look at traits using generic types (or type parameters) and traits with associated types in Rust. What is the difference and when does it make sense to use one over the other?]]></description><link>https://blog.thomasheartman.com/posts/on-generics-and-associated-types</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/on-generics-and-associated-types</guid><pubDate>Mon, 30 Mar 2020 08:05:57 GMT</pubDate><content:encoded>&lt;p&gt;Compared to other languages I&apos;ve learned, Rust has a fair few concepts that can be a bit tricky to get your head around. Borrowing, ownership, and the borrow-checker are common enough to have spawned a range of memes on their own, and I&apos;ve personally spent hours on lifetime issues only to give up and rewrite something using cloning.&lt;/p&gt;&lt;p&gt;&lt;i&gt;Associated types&lt;/i&gt;, though not something that&apos;ll have you banging your head on your desk for hours, is something that it took me quite a few tries to finally understand---or at least think I understand.&lt;/p&gt;&lt;p&gt;What really never stuck was how it was different from generics, and why you&apos;d need (or event &lt;i&gt;want&lt;/i&gt;) associated types. So what&apos;s a good way to learn and internalize a topic like this? Well, write something down and release it to the internet, of course! They&apos;ll let you know if you&apos;re wrong.&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;tl;dr:&lt;/h2&gt;&lt;p&gt;The quick and dirty answer to when to use generics and when to use associated types is: Use generics if it makes sense to have multiple implementations of a trait for a specific type (such as the &lt;code&gt;From&amp;#x3C;T&gt;&lt;/code&gt; trait). Otherwise, use associated types (like &lt;code&gt;Iterator&lt;/code&gt; and &lt;code&gt;Deref&lt;/code&gt;).&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Goals and constraints of this post&lt;/h2&gt;&lt;p&gt;This post is intended to demonstrate and explain the differences and similarities between associated types and generic types. It will deal specifically with traits, as this is the only place where associated types come into play.&lt;/p&gt;&lt;p&gt;Furthermore, even if we&apos;re talking about associated types, we will not venture into the dark forest of &lt;i&gt;generic&lt;/i&gt; associated types. However, if you&apos;re curious about this and haven&apos;t kept up to date, I encourage you to look through &lt;a href=&quot;https://github.com/rust-lang/rfcs/blob/master/text/1598-generic_associated_types.md&quot;&gt;the RFC&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;If, after reading this post, you&apos;re still not sure what I&apos;m on about, check out the &lt;a href=&quot;https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#default-generic-type-parameters-and-operator-overloading&quot;&gt;/Advanced Traits/ chapter&lt;/a&gt; of the Book, and specifically the section on &lt;a href=&quot;https://doc.rust-lang.org/1.29.0/book/2018-edition/ch19-03-advanced-traits.html?highlight=associated,types#specifying-placeholder-types-in-trait-definitions-with-associated-types&quot;&gt;associated types&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Finally, this post assumes you have some familiarity with programming (and with Rust specifically), and with some forms of generic programming. For a primer on generic types in Rust, check out &lt;a href=&quot;https://doc.rust-lang.org/book/ch10-01-syntax.html&quot;&gt;Chapter 10.1, /Generic Data Types/,&lt;/a&gt; of the book&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Definitions&lt;/h2&gt;&lt;p&gt;To make sure we&apos;re all on the same page, let&apos;s have some quick definitions to start us off, shall we?&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Generic types&lt;/h3&gt;&lt;p&gt;In the context of traits, &lt;strong&gt;generic types&lt;/strong&gt;, also known as &lt;strong&gt;type parameters&lt;/strong&gt;, are a way of deferring the specific types that your trait uses until the trait is implemented. Generic types can be completely open, such that any type would work, or they can be constrained to types that implement some trait.&lt;/p&gt;&lt;p&gt;Take, for instance, Rust&apos;s &lt;a href=&quot;https://doc.rust-lang.org/std/convert/trait.From.html&quot;&gt;~std::convert::From&amp;#x3C;T&gt;~ trait&lt;/a&gt;. The &lt;code&gt;T&lt;/code&gt; in the type signature says that this type is generic over any type &lt;code&gt;T&lt;/code&gt; &lt;sup id=&quot;fnr-2&quot; class=&quot;footnote-ref&quot; data-label=&quot;2&quot;&gt;&lt;a href=&quot;#fn-2&quot;&gt;[2]&lt;/a&gt;&lt;/sup&gt;, meaning you can convert any type &lt;code&gt;T&lt;/code&gt; into the type you&apos;re implementing the trait for.&lt;/p&gt;&lt;p&gt;Constrained (or &lt;i&gt;bounded&lt;/i&gt;) generic types are more often seen in generic functions than in generic traits, but what they do is allow the author of trait &lt;code&gt;X&lt;/code&gt; to say that &apos;only types which implement &lt;i&gt;some other trait ~Y~&lt;/i&gt; can be used for this trait&apos;. We&apos;ll see examples of this later, so don&apos;t worry if it&apos;s a bit fuzzy right now.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Associated types&lt;/h3&gt;&lt;p&gt;&lt;strong&gt;Associated types&lt;/strong&gt; are, as the name implies, types that are &lt;i&gt;associated&lt;/i&gt; with a trait. When you define the trait, the type is still unspecified. Much like with generics, you can put constraints on the type if you want to, or you can choose not to.&lt;/p&gt;&lt;p&gt;One of the most prominent examples of a trait with associated types is the &lt;a href=&quot;https://doc.rust-lang.org/std/iter/trait.Iterator.html&quot;&gt;~Iterator~ trait&lt;/a&gt;. The &lt;code&gt;Iterator&lt;/code&gt; trait has an associated type &lt;code&gt;Item&lt;/code&gt; and a function &lt;code&gt;next&lt;/code&gt;. The &lt;code&gt;next&lt;/code&gt; function returns an &lt;code&gt;Option&amp;#x3C;Self::Item&gt;&lt;/code&gt;. You could have done the same thing with generic types, but, as we&apos;ll see later, using associated types offer some benefits in certain situations.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Syntax&lt;/h2&gt;&lt;p&gt;Before we go any further, let&apos;s just quickly review the syntax for these concepts. If for no other reason, then just to make everything a bit less abstract. We&apos;ll define two traits, &lt;code&gt;Generic&lt;/code&gt; and &lt;code&gt;Associated&lt;/code&gt;, which use generics and associated types respectively, and we&apos;ll look at using bounds and default types as well.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Basic traits&lt;/h3&gt;&lt;p&gt;A type-parameterized trait can look a little something like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Generic&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T&gt; {
    &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;get&lt;/span&gt;&lt;/span&gt;(&amp;#x26;&lt;span class=&quot;hljs-keyword&quot;&gt;self&lt;/span&gt;) -&gt; T;
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Similarly, a similar trait with an associated type looks like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Associated&lt;/span&gt;&lt;/span&gt; {
    &lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;T&lt;/span&gt;&lt;/span&gt;;
    &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;get&lt;/span&gt;&lt;/span&gt;(&amp;#x26;&lt;span class=&quot;hljs-keyword&quot;&gt;self&lt;/span&gt;) -&gt; Self::T;
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note how the type gets moved from the type signature and into the trait definition itself, and how, when referencing it later, we need to use &lt;code&gt;Self::T&lt;/code&gt;, instead of just &lt;code&gt;T&lt;/code&gt;.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;With constraints&lt;/h3&gt;&lt;p&gt;If we want to set constraints on the associated type or type parameter, we use the same syntax as Rust uses everywhere else for bounds: the &lt;code&gt;:&lt;/code&gt; operator.&lt;/p&gt;&lt;p&gt;For instance, say we want to constrain our types to only types that implement the &lt;code&gt;core::fmt::Display&lt;/code&gt; trait:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Generic&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T: Display&gt; {
    &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;get&lt;/span&gt;&lt;/span&gt;(&amp;#x26;&lt;span class=&quot;hljs-keyword&quot;&gt;self&lt;/span&gt;) -&gt; T;
}

&lt;span class=&quot;hljs-comment&quot;&gt;// or using the `where` keyword&lt;/span&gt;
&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Generic&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;
    T: Display,
{
    &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;get&lt;/span&gt;&lt;/span&gt;(&amp;#x26;&lt;span class=&quot;hljs-keyword&quot;&gt;self&lt;/span&gt;) -&gt; T;
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;With associated types, the syntax is much the same:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Associated&lt;/span&gt;&lt;/span&gt; {
    &lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;T&lt;/span&gt;&lt;/span&gt;: Display;
    &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;get&lt;/span&gt;&lt;/span&gt;(&amp;#x26;&lt;span class=&quot;hljs-keyword&quot;&gt;self&lt;/span&gt;) -&gt; Self::T;
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;With default types&lt;/h3&gt;&lt;p&gt;Rust has a cool feature for generic types where you can set the &lt;i&gt;default type&lt;/i&gt;, which will be assumed if no type is specified. This can be useful if, for most use cases, you want to use a specific type, but want to be able to override it sometimes. See &lt;a href=&quot;https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#default-generic-type-parameters-and-operator-overloading&quot;&gt;the section on default generic types&lt;/a&gt; in the Book for more information.&lt;/p&gt;&lt;p&gt;They look like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// basic trait, no constraint&lt;/span&gt;
&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Generic&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T = &lt;span class=&quot;hljs-built_in&quot;&gt;String&lt;/span&gt;&gt; {
    &lt;span class=&quot;hljs-comment&quot;&gt;// ...&lt;/span&gt;
}

&lt;span class=&quot;hljs-comment&quot;&gt;// with constraint&lt;/span&gt;
&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Generic&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T: Display = &lt;span class=&quot;hljs-built_in&quot;&gt;String&lt;/span&gt;&gt; {
    &lt;span class=&quot;hljs-comment&quot;&gt;// ...&lt;/span&gt;
}

&lt;span class=&quot;hljs-comment&quot;&gt;// or using the `where` clause&lt;/span&gt;
&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Generic&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T = &lt;span class=&quot;hljs-built_in&quot;&gt;String&lt;/span&gt;&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;
    T: Display,
{
    &lt;span class=&quot;hljs-comment&quot;&gt;// ...&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;From what I tried, it seems you cannot put the default type (&lt;code&gt;= String&lt;/code&gt;) in the &lt;code&gt;where&lt;/code&gt; clause of the trait.&lt;/p&gt;&lt;p&gt;For associated types, there is no such thing as default types on stable rust today. However, if you&apos;re on nightly, you can use the &lt;code&gt;#![feature(associated_type_defaults)]&lt;/code&gt; flag, which enables this. Judging from the &lt;a href=&quot;https://github.com/rust-lang/rust/issues/29661&quot;&gt;GitHub tracking issue&lt;/a&gt;, this &lt;i&gt;is&lt;/i&gt; being worked on but I&apos;ve not seen anything about stabilization of this yet.&lt;/p&gt;&lt;p&gt;But let&apos;s see what it&apos;d look like:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-meta&quot;&gt;#![feature(associated_type_defaults)]&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;// simple&lt;/span&gt;
&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Associated&lt;/span&gt;&lt;/span&gt; {
    &lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;T&lt;/span&gt;&lt;/span&gt; = &lt;span class=&quot;hljs-built_in&quot;&gt;String&lt;/span&gt;;
    &lt;span class=&quot;hljs-comment&quot;&gt;// ...&lt;/span&gt;
}

&lt;span class=&quot;hljs-comment&quot;&gt;// with constraint&lt;/span&gt;
&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Associated&lt;/span&gt;&lt;/span&gt; {
    &lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;T&lt;/span&gt;&lt;/span&gt;: Display = &lt;span class=&quot;hljs-built_in&quot;&gt;String&lt;/span&gt;;
    &lt;span class=&quot;hljs-comment&quot;&gt;// ...&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;It&apos;s pretty neat and pretty similar. You could even do something like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;trait&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Associated&lt;/span&gt;&lt;/span&gt; {
    &lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;T&lt;/span&gt;&lt;/span&gt;: Display = &lt;span class=&quot;hljs-built_in&quot;&gt;String&lt;/span&gt;;
    &lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;U&lt;/span&gt;&lt;/span&gt; = Self::T;
    &lt;span class=&quot;hljs-comment&quot;&gt;// ...&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Don&apos;t know when it&apos;d be useful, but it&apos;s nifty 🤷&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Commonalities&lt;/h2&gt;&lt;p&gt;Now that we&apos;ve covered what they are and what the syntax looks like, let&apos;s continue by looking at what they have in common.&lt;/p&gt;&lt;p&gt;The most important thing is that both generics and associated types allow you to defer the decision of what type to use for the trait implementation. Even if the notation is a bit different, anywhere you have an associated type, you can replace it with a generic type instead (though the opposite does not hold true). As the &lt;a href=&quot;https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md&quot;&gt;the RFC&lt;/a&gt; puts it: &quot;associated types do not increase the expressiveness of traits per se, because you can always use extra type parameters to a trait instead&quot;. However, they do offer other benefits.&lt;/p&gt;&lt;p&gt;The fact that you can always use generics instead of associated types is why it took me so long to understand what associated types exist for. As we move into the next section, we&apos;ll examine what makes them different, and why you&apos;d want to choose one over the other.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Differences&lt;/h2&gt;&lt;p&gt;As we&apos;ve seen, generics and associated types cover a lot of the same use cases, but there are some reasons why you might choose one over the other.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Generics&lt;/strong&gt; allow you to implement the same trait numerous times for the same type by changing the type parameter. The &lt;code&gt;From&amp;#x3C;T&gt;&lt;/code&gt; trait was mentioned earlier, and it&apos;s a great example of this. Because &lt;code&gt;From&amp;#x3C;T&gt;&lt;/code&gt; uses a generic type, we can implement it for any number of type parameters.&lt;/p&gt;&lt;p&gt;For instance, say you have a type &lt;code&gt;MyNumeric&lt;/code&gt;. You can implement &lt;code&gt;From&amp;#x3C;u8&gt;&lt;/code&gt;, &lt;code&gt;From&amp;#x3C;u16&gt;&lt;/code&gt;, &lt;code&gt;From&amp;#x3C;u32&gt;&lt;/code&gt;, and so on. This makes generics very useful if it makes sense to have multiple trait implementations varying only in type parameters.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Associated types&lt;/strong&gt;, on the other hand, only allow &lt;strong&gt;a single implementation&lt;/strong&gt;. Because a type can only implement a trait once, this can be used to constrain the number of implementations.&lt;/p&gt;&lt;p&gt;The &lt;a href=&quot;https://doc.rust-lang.org/std/ops/trait.Deref.html&quot;&gt;~Deref~ trait&lt;/a&gt; comes to mind. &lt;code&gt;Deref&lt;/code&gt; has an associated type &lt;code&gt;Target&lt;/code&gt;, which it can be dereferenced to. It would get really confusing if a type could implement &lt;code&gt;Deref&lt;/code&gt; into an arbitrary set of other types (and probably &lt;i&gt;very&lt;/i&gt; tricky for type inference!).&lt;/p&gt;&lt;p&gt;Because a trait can only be implemented once per type, associated types also offer some notational benefits. Using associated types means you don&apos;t have to add type annotations for all the extra types. This is touted as an engineering benefit in &lt;a href=&quot;https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md&quot;&gt;the RFC&lt;/a&gt;.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Summary and further reading&lt;/h2&gt;&lt;p&gt;In short, use generics when you want to a type &lt;code&gt;A&lt;/code&gt; to be able to implement a trait any number of times for different type parameters, such as in the case of the &lt;code&gt;From&amp;#x3C;T&gt;&lt;/code&gt; trait.&lt;/p&gt;&lt;p&gt;Use associated types if it makes sense for a type to only implement the trait once, such as with &lt;code&gt;Iterator&lt;/code&gt; and &lt;code&gt;Deref&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;If you want to know more about associated types and what problems they solve, I recommend starting with &lt;a href=&quot;https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md&quot;&gt;the RFC that introduced them&lt;/a&gt; and the &lt;a href=&quot;https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types&quot;&gt;section on associated types in the Book&lt;/a&gt;. The &lt;a href=&quot;https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#default-generic-type-parameters-and-operator-overloading&quot;&gt;section on the ~Add~ trait&lt;/a&gt;, which uses both generics (with defaults) &lt;i&gt;and&lt;/i&gt; associated types, is also well worth a read. As an alternative resource, &lt;a href=&quot;https://stackoverflow.com/a/32065644&quot;&gt;this Stack Overflow response&lt;/a&gt; also contains a well-worded explanation, with examples, of when you&apos;d use one over the other.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;/div&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;This is mostly said in jest. I haven&apos;t actually gotten very many corrections on statements I&apos;ve made at all; and the ones I &lt;i&gt;have&lt;/i&gt; had, have always been very nice. I like you, reader. You&apos;re my friend.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[2]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-2&quot; class=&quot;footnote&quot; data-label=&quot;2&quot;&gt;&lt;p&gt;&lt;i&gt;Well, actually&lt;/i&gt;, it says that this type is generic over any type &lt;code&gt;T&lt;/code&gt; that implements the &lt;code&gt;Sized&lt;/code&gt; trait. We&apos;ll gloss over this in this article, but for more information, check out &lt;a href=&quot;https://doc.rust-lang.org/1.29.0/book/2018-edition/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait&quot;&gt;this section from chapter 19.4, /Advanced Functions and Closures/, of the Book&lt;/a&gt;.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dl id=&quot;footnotes&quot;&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;This is mostly said in jest. I haven&apos;t actually gotten very many corrections on statements I&apos;ve made at all; and the ones I &lt;i&gt;have&lt;/i&gt; had, have always been very nice. I like you, reader. You&apos;re my friend.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[2]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-2&quot; class=&quot;footnote&quot; data-label=&quot;2&quot;&gt;&lt;p&gt;&lt;i&gt;Well, actually&lt;/i&gt;, it says that this type is generic over any type &lt;code&gt;T&lt;/code&gt; that implements the &lt;code&gt;Sized&lt;/code&gt; trait. We&apos;ll gloss over this in this article, but for more information, check out &lt;a href=&quot;https://doc.rust-lang.org/1.29.0/book/2018-edition/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait&quot;&gt;this section from chapter 19.4, /Advanced Functions and Closures/, of the Book&lt;/a&gt;.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;/dl&gt;</content:encoded></item><item><title><![CDATA[Let's read: Haskell Programming from First Principles, pt XI]]></title><description><![CDATA[In which we read the 11th chapter of 'Haskell Programming from First Principles': Algebraic Data Types and discuss higher-kinded types, cardinality in relation to the type system, and how the function type is exponential. Pokémon make an appearance too!]]></description><link>https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-xi</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-xi</guid><pubDate>Mon, 23 Mar 2020 08:20:58 GMT</pubDate><content:encoded>&lt;p&gt;Let&apos;s get this out of the way before we go any further: This is a massive chapter. There is a &lt;i&gt;so much&lt;/i&gt; content in here, and there is no way that I&apos;ll be able to summarize it all in one neatly packaged post. Instead, I&apos;ll be focusing on the things that struck me as particularly important: &lt;strong&gt;kinds&lt;/strong&gt; and &lt;strong&gt;cardinality&lt;/strong&gt;.&lt;/p&gt;&lt;p&gt;That means that in exchange for covering a few topics more thoroughly, I will &lt;i&gt;not&lt;/i&gt; be devoting many words to &lt;a href=&quot;https://wiki.haskell.org/Newtype&quot;&gt;/newtypes/&lt;/a&gt;, &lt;a href=&quot;https://en.wikipedia.org/wiki/Arity&quot;&gt;arity&lt;/a&gt;, what &lt;i&gt;sum&lt;/i&gt; and &lt;i&gt;product types&lt;/i&gt; are (see &lt;a href=&quot;https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-iv/&quot;&gt;chapter 4&lt;/a&gt; and &lt;a href=&quot;https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-ix&quot;&gt;chapter 9&lt;/a&gt;), or constructing and deconstructing data types (see &lt;a href=&quot;https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-viia/&quot;&gt;chapter 7a&lt;/a&gt;).&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Kinds&lt;/h2&gt;&lt;pre class=&quot;aside&quot;&gt;This section has several references to the data type known as ~Maybe~. We have not covered this data type previously in this series, so a short introduction is in order if you&apos;re not already familiar with it.

~Maybe~ is used to model data that you may or may not have. It has two data constructors: ~Just~ and ~Nothing~, takes one type parameter, and is in some ways similar to how a lot of other languages have a ~null~ value, though more robust. It is similar to the ~Option~ type in other languages such as Rust, OCaml, and F#.

The data declaration is as follows:
#+begin_src haskell
  data Maybe a = Just a | Nothing
      deriving (Eq, Ord)
#+end_src

For more information, please see the [[https://wiki.haskell.org/Maybe][Haskell wiki article]].&lt;/pre&gt;&lt;p&gt;&lt;i&gt;Kinds&lt;/i&gt; are to types what types are to terms. Or, put differently, a kind can be seen as a &lt;i&gt;type constructor&apos;s type&lt;/i&gt; or as a &lt;i&gt;type one level up&lt;/i&gt;. It sounds convoluted, but bear with me.&lt;/p&gt;&lt;p&gt;Keep in mind that, as covered in &lt;a href=&quot;https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-iv/&quot;&gt;chapter 4&lt;/a&gt;, a &lt;i&gt;type constructor&lt;/i&gt; is one of two constructor types in Haskell (the other being data constructors). It is the name of the type. Type constructors are used only at the type level, in type signatures, and in typeclass declarations and instances.&lt;/p&gt;&lt;p&gt;We represent kinds with the &lt;code&gt;*&lt;/code&gt; symbol. If you have a fully applied, concrete type constructor, such as &lt;code&gt;Bool&lt;/code&gt; or &lt;code&gt;[Int]&lt;/code&gt;, then the kind is &lt;code&gt;*&lt;/code&gt;. If you have a type constructor that is still waiting for a type parameter---such as &lt;code&gt;Maybe&lt;/code&gt;---then that has the kind &lt;code&gt;* -&gt; *&lt;/code&gt;. A kind is not a type until it is fully applied. In other words, &lt;code&gt;Maybe&lt;/code&gt; isn&apos;t a type, but &lt;code&gt;Maybe String&lt;/code&gt;  &lt;i&gt;is&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;Second, we only talk about kinds on the &lt;i&gt;type&lt;/i&gt; level. That is, &lt;code&gt;Bool&lt;/code&gt; is a &lt;i&gt;type&lt;/i&gt; and has kind &lt;code&gt;*&lt;/code&gt;. &lt;code&gt;False&lt;/code&gt; is a term (or value) and does not have a kind. For data constructors that share names with their type constructors (e.g. &lt;code&gt;[]&lt;/code&gt;), this can be confusing, but remember that kinds only operate on type level constructors.&lt;/p&gt;&lt;p&gt;To make this clearer, let&apos;s turn to the ever faithful GHCi. To print the kind of a type constructor, we use the &lt;code&gt;:k&lt;/code&gt; (or &lt;code&gt;:kind&lt;/code&gt;) command followed by the constructor we want information on. Let&apos;s have a couple of examples and see what we can learn.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;Prelude&gt; :k Bool
Bool :: *&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;code&gt;Bool&lt;/code&gt; is a fully applied type in and of itself. it takes no type parameters and as such has kind &lt;code&gt;*&lt;/code&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;Prelude&gt; :k Maybe
Maybe :: * -&gt; *&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;code&gt;Maybe&lt;/code&gt; is our first &lt;i&gt;higher-kinded type&lt;/i&gt; (more on that in a bit), which means it&apos;s a type constructor that requires another type before it&apos;s complete. In other words, you couldn&apos;t simply put &lt;code&gt;Maybe&lt;/code&gt; in a type signature without saying &lt;i&gt;what type&lt;/i&gt; of maybe it is.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;Prelude&gt; :k Maybe Integer
Maybe Integer :: *&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;code&gt;Maybe Integer&lt;/code&gt;, on the other hand, is a concrete type. As opposed to just &lt;code&gt;Maybe&lt;/code&gt; above, we also know what the type is (&lt;code&gt;Integer&lt;/code&gt;). As such, it is fully applied and of kind &lt;code&gt;*&lt;/code&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;Prelude&gt; :k (,)
(,) :: * -&gt; * -&gt; *&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This one is quite interesting. This is the type constructor for a tuple. Without any type parameters, it&apos;s of kind &lt;code&gt;* -&gt; * -&gt; *&lt;/code&gt; because it needs two types to be fully applied.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Higher-kinded types&lt;/h3&gt;&lt;p&gt;According to the book, there are only &apos;a few&apos; kinds, and the default (and the only one covered in this chapter) is &lt;code&gt;*&lt;/code&gt;. Kind signatures work the same as type signatures, i.e. using the same &lt;code&gt;::&lt;/code&gt; and &lt;code&gt;-&gt;&lt;/code&gt; syntax.&lt;/p&gt;&lt;p&gt;&lt;i&gt;Higher-kinded types&lt;/i&gt; are types that require type parameters to be fully applied, to become real types---that is, their kind is at least &lt;code&gt;* -&gt; *&lt;/code&gt;. Lists, tuples, and &lt;code&gt;Maybe&lt;/code&gt; are good examples of higher-kinded types.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Cardinality&lt;/h2&gt;&lt;p&gt;The &lt;i&gt;cardinality&lt;/i&gt; of a type is the number of different values it defines. A value defined by a type is also known as an &lt;i&gt;inhabitant&lt;/i&gt; of said type. Types&apos; cardinalities can be anywhere from as small as 0 (&lt;a href=&quot;https://wiki.haskell.org/Empty_type&quot;&gt;empty types&lt;/a&gt;) and as large as infinite.&lt;/p&gt;&lt;p&gt;To demonstrate this concept we&apos;ll use these arbitrary sum types, modeled after the starters in the mainline Pokémon games (&lt;a href=&quot;https://en.wikipedia.org/wiki/Pok%C3%A9mon_Gold_and_Silver&quot;&gt;just pretend we&apos;re in 1999&lt;/a&gt; for simplicity&apos;s sake):&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;StarterType&lt;/span&gt;&lt;/span&gt;
  = &lt;span class=&quot;hljs-type&quot;&gt;Grass&lt;/span&gt;
  | &lt;span class=&quot;hljs-type&quot;&gt;Fire&lt;/span&gt;
  | &lt;span class=&quot;hljs-type&quot;&gt;Water&lt;/span&gt;

&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Starter&lt;/span&gt;&lt;/span&gt;
  = &lt;span class=&quot;hljs-type&quot;&gt;GenI&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;StarterType&lt;/span&gt;
  | &lt;span class=&quot;hljs-type&quot;&gt;GenII&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;StarterType&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The cardinality of &lt;code&gt;StarterType&lt;/code&gt; is 3 because it has only three possible inhabitants. The cardinality of &lt;code&gt;Starter&lt;/code&gt; is 6, because it has two data constructors, each of which also require a &lt;code&gt;StarterType&lt;/code&gt;. As such, we get 2 \cdot 3 (or 3 + 3), which is 6.&lt;/p&gt;&lt;p&gt;Above, the &lt;code&gt;Starter&lt;/code&gt; type demonstrates why it&apos;s called a sum type: We can calculate the cardinality of the type by &lt;i&gt;summing&lt;/i&gt; the number of possible values of each of it&apos;s data constructors.&lt;/p&gt;&lt;p&gt;If you&apos;ve got a friend with a link cable, then maybe you&apos;ve traded some pocket monsters and ended up with two starters---lucky you! In this case, you now have a tuple of starters, i.e. &lt;code&gt;(Starter, Starter)&lt;/code&gt;. A tuple is a product type, so that means we find the cardinality by multiplying the cardinality of each of its contained types. As such, the cardinality of &lt;code&gt;(Starter, Starter)&lt;/code&gt; is 6 \cdot 6 = 36.&lt;/p&gt;&lt;p&gt;This is the basic concept of cardinality in types. It&apos;s pretty straightforward, and it&apos;s a good thing to keep in mind when designing systems.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;The function type is exponential&lt;/h3&gt;&lt;p&gt;We&apos;ve seen that sum types are the addition operator and that product types are the multiplication operator when it comes to calculating inhabitants of types. However, we haven&apos;t mentioned function types, which act as the exponent operator: given a function &lt;code&gt;a -&gt; b&lt;/code&gt;, the formula for the number of inhabitants is b^a. So if we have a function &lt;code&gt;StarterType -&gt; Bool&lt;/code&gt;, for instance, the number of possible implementations is 2^3 = 8. This relationship continues as the number of parameters increases, so for &lt;code&gt;a -&gt; b -&gt; c&lt;/code&gt; it&apos;s equal to  c^{ba} (or &lt;code&gt;(c ^ b) ^ a&lt;/code&gt;).&lt;/p&gt;&lt;p&gt;If this is a bit confusing: don&apos;t worry, I&apos;m right there with ya. But let&apos;s give it a go. Let&apos;s write out all possible permutations of the function &lt;code&gt;StarterType -&gt; Bool&lt;/code&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter1&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;StarterType&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter1&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Grass&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter1&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Fire&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter1&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Water&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;

&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter2&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;StarterType&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter2&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Grass&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter2&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Fire&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter2&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Water&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt;

&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter3&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;StarterType&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter3&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Grass&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter3&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Fire&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter3&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Water&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;

&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter4&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;StarterType&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter4&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Grass&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter4&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Fire&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter4&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Water&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;

&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter5&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;StarterType&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter5&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Grass&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter5&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Fire&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter5&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Water&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;

&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter6&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;StarterType&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter6&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Grass&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter6&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Fire&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter6&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Water&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt;

&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter7&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;StarterType&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter7&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Grass&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter7&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Fire&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter7&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Water&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt;

&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter8&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;StarterType&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter8&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Grass&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter8&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Fire&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;acceptStarter8&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Water&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Whew. And that&apos;s with only two possible result values and three possible inputs. Yeah, this gets wild pretty quickly.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Closing up&lt;/h2&gt;&lt;p&gt;While the format is a bit different from previous posts in the series, I hope you found something useful here too. The rest of what the chapter covers is definitely interesting, but not eye-opening in the way that kinds and cardinality are. The next chapter is on handling errors and includes &lt;code&gt;Maybe&lt;/code&gt;, &lt;code&gt;Either&lt;/code&gt;, more higher-kindedness, and &lt;i&gt;anamorphisms&lt;/i&gt; (if that sounds interesting, why not check out &lt;a href=&quot;https://blog.thomasheartman.com/posts/corecursion-and-anamorphisms/&quot;&gt;this post on corecursion and anamorphisms&lt;/a&gt; in the meantime?). Stay tuned, and it should land at some unspecified future date.&lt;/p&gt;&lt;p&gt;Until next time: stay safe.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Improve your workflow with Forge]]></title><description><![CDATA[In which I gush about my new favorite tool for working with GitLab: Magit Forge. Forge is an extension to the already extremely useful Magit, that integrates with the likes of GitHub and GitLab, letting you collaborate on issues and PRs without leaving Emacs.]]></description><link>https://blog.thomasheartman.com/posts/improve-your-workflow-with-forge</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/improve-your-workflow-with-forge</guid><pubDate>Mon, 16 Mar 2020 08:20:30 GMT</pubDate><content:encoded>&lt;p&gt;Some tools are so good that once you start using them, you can&apos;t imagine &lt;i&gt;not&lt;/i&gt; using them. &lt;a href=&quot;https://magit.vc/&quot;&gt;Magit&lt;/a&gt; is one such tool. If you&apos;re also working with GitHub or GitLab, you can use &lt;a href=&quot;https://github.com/magit/forge&quot;&gt;Forge&lt;/a&gt; to make life even better.&lt;/p&gt;&lt;p&gt;In this post, I&apos;ll be giving a brief overview of what Forge is, how to get started (well, at least what&apos;s not in the manual), and the problems I ran into.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Magit and Forge&lt;/h2&gt;&lt;p&gt;Magit is a &apos;Git porcelain inside Emacs&apos;. In other words, it&apos;s a Git UI inside Emacs, providing access to repo status and a number of different commands. Magit is so good, that even if I used another editor for developing (&lt;i&gt;hah, as if!&lt;/i&gt;), I&apos;d still switch back to Emacs to handle my Git business.&lt;/p&gt;&lt;p&gt;Forge is a Magit extension that allows deeper integration with certain /forges/&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;, such as GitHub and GitLab. For instance, when using GitLab, it allows you to create and comment on issues and pull requests, assign tasks, add labels (with auto-complete), open and close issues and more; all from within Emacs.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Motivation and early impressions&lt;/h2&gt;&lt;p&gt;After &lt;a href=&quot;https://www.reddit.com/r/emacs/comments/fjs4vo/blog_post_magit_forge_level_up_your_workflow/&quot;&gt;posting this article to Reddit&lt;/a&gt;, I was asked about my motivation for using Forge over the GitLab UI. This section attempts to outline why I wanted to switch and what my impressions are after having used it actively for work for a couple of days.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Why not the GitLab UI?&lt;/h3&gt;&lt;p&gt;I use GitLab for work, and while I think it&apos;s great in a lot of respects, it also has its share of issues, especially with the user interface. In general, navigating between projects, issue boards, and merge requests is very clunky and takes far too many clicks for it to be a good experience.&lt;/p&gt;&lt;p&gt;Because of this, I have bookmarked various projects&apos; merge request overviews and issue boards, and use the bookmarks for navigating. It&apos;s not ideal, but it works tolerably well.&lt;/p&gt;&lt;p&gt;What doesn&apos;t work very well, however, is creating issues or merge requests. Not only do you need to write fairly long-form content, but you will also frequently want to add &apos;labels&apos; or assign someone to a task. GitLab does have so-called &lt;a href=&quot;https://docs.gitlab.com/ee/user/project/quick_actions.html&quot;&gt;/quick actions/&lt;/a&gt;, but they don&apos;t seem to work when used in the web UI.&lt;/p&gt;&lt;p&gt;This means writing and editing text in plain HTML text areas (without your favorite key bindings) and then having to use your mouse to navigate a UI, find multiple searchable lists of elements and filter and find the items you&apos;re looking for.&lt;/p&gt;&lt;p&gt;Overall: not a great experience.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h4&gt;Other options&lt;/h4&gt;&lt;p&gt;As was pointed out in the Reddit thread, there are a number of ways to deal with the web UI issue. Notable contenders are &lt;a href=&quot;https://www.emacswiki.org/emacs/Edit_with_Emacs&quot;&gt;the /Edit with Emacs/ extension&lt;/a&gt; for Chrome and Firefox, &lt;a href=&quot;https://github.com/manateelazycat/emacs-application-framework&quot;&gt;Emacs Application Framework&lt;/a&gt;  (&lt;i&gt;EAF&lt;/i&gt;) and it&apos;s browser, and &lt;a href=&quot;https://chrome.google.com/webstore/detail/vimium/dbepggeogbaibhgnhhndojpepiihcmeb&quot;&gt;Vimium&lt;/a&gt; and &lt;a href=&quot;https://github.com/brookhong/Surfingkeys&quot;&gt;Surfingkeys&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;I&apos;m already a heavy user of Surfingkeys (though I realize I still have a &lt;strong&gt;lot&lt;/strong&gt; of key bindings to internalize), and it&apos;s great for navigating your average website, but GitLab has so many things you can click on and interact with that it gets quite messy.&lt;/p&gt;&lt;p&gt;I tried Edit with Emacs, and while it&apos;s a really neat way to interact with text, it wasn&apos;t for me (for GitLab). I still had to activate it using my mouse, and it didn&apos;t relieve me from using the mouse to interact with the label and assignment menus either.&lt;/p&gt;&lt;p&gt;As for Emacs Application Framework, I&apos;d never heard of it before. It looks super cool, but I&apos;m a bit scared that if I go down that road, I&apos;ll never make it out alive. Further, &lt;a href=&quot;https://www.reddit.com/r/emacs/comments/fjs4vo/blog_post_magit_forge_level_up_your_workflow/fkrfee3?utm_source=share&amp;#x26;utm_medium=web2x&quot;&gt;this post&lt;/a&gt; by &lt;a href=&quot;https://www.reddit.com/user/DarkNightened/&quot;&gt;u/DarkNightened&lt;/a&gt; has some really good points on why the EAF might not be the right fit for this use case (as well as some pretty 🔥 Surfingkeys tips).&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Early impressions&lt;/h3&gt;&lt;p&gt;After having used Forge for a few more days, my impression is overwhelmingly positive. There are a few things it doesn&apos;t do, but I imagine some of that may be limited by the API that GitLab exposes. It also seems like GitHub receives more attention than GitLab, so it&apos;s quite possible that that integration has more features.&lt;/p&gt;&lt;p&gt;In the following sections, I&apos;ll be referring to issues and merge requests (&lt;i&gt;MRs&lt;/i&gt;) collectively as &lt;i&gt;topics&lt;/i&gt;, which is what Forge calls them.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h4&gt;The good parts&lt;/h4&gt;&lt;ul&gt;&lt;li&gt;Issues and MRs in the Magit status buffer ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;This is the most basic thing that Forge gives you. In addition to just displaying these topics, it also displays labels (correctly color-coded) and whether a topic is open or not. If you expand an MR it&apos;ll list the commits it is made of. Viewing one of these items (by pressing &lt;code&gt;&amp;#x3C;RET&gt;&lt;/code&gt;) will also display assignees, all related comments and actions that have been taken.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Easy creation of issues and MRs from within Emacs ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Of all the things that Forge does, this is what I wanted more than anything. I&apos;m pleased to say that it works incredibly well. There are a few things that you can&apos;t do from Emacs (see the next section), but these are minor issues.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Autocomplete on typing when referencing issues and MRs, assigning users and labels  ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;This one took me by surprise, but when you start typing out a topic ID (prefixed with &lt;code&gt;#&lt;/code&gt; for issues or &lt;code&gt;!&lt;/code&gt; for MRs) you get auto-completion on topics in the project. The completion candidates show not only the ID, but also the topic title. This is super handy if you&apos;re adding related topics or otherwise want to reference them. This applies to seemingly all Magit buffers, including buffers for topic creation and for commit messages.&lt;/p&gt;&lt;p&gt;You&apos;ll also gain tab completion when assigning users to a topic or adding labels.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Quick copy a link to any topic, or open the topic in your browser ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Opening a topic in your browser comes with a default key binding, and there is a function for adding the URL of the topic at point to your kill ring (&lt;code&gt;forge-copy-url-at-point-as-kill&lt;/code&gt;). The latter wasn&apos;t bound to a key by default, but it&apos;s a very useful command when you need to share the link to a topic with a coworker or the like.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Viewing and checking out MRs is a breeze ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;It is incredibly easy to check out and create a branch from a merge request. Not much more to say about this, really. See the &lt;a href=&quot;https://magit.vc/manual/forge/Branching.html#Branching&quot;&gt;section on branching in the manual&lt;/a&gt; for more information.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h4&gt;The not-so-good parts&lt;/h4&gt;&lt;ul&gt;&lt;li&gt;Certain values can&apos;t be set from Emacs ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;When creating merge requests, I haven&apos;t been able to specify that a merge request requires approval before being merged or that the source branch should be deleted after the merge. It&apos;s a minor thing, but it&apos;s something we do all the time on the team I&apos;m on, so it&apos;d be a nice feature to have.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Merge requests show diff between local branches ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Say you make a few commits to the master branch (without pushing) before branching off, making a few more commits, and creating a merge request. Forge shows this MR as only containing the commits you made after branching off from master, even if the first commits you made to master haven&apos;t been pushed to the remote.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;May (or may not) affect Magit performance ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;This is very uncertain and probably inaccurate. Magit has felt a bit slow over the past couple of days, but my machine is under quite heavy load, so I don&apos;t actually think it&apos;s been any slower than usual. All Forge updates should be performed asynchronously, so it shouldn&apos;t have a noticeable impact. However, when the minibuffer says &apos;pulling &amp;#x3C;repo&gt;&apos;, my mind tends to automatically assume that Emacs isn&apos;t ready before the pull is successful. It does however relate to the next thing:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Updates to topics aren&apos;t &apos;optimistic&apos; ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;When you make a change in Emacs, Forge goes ahead and tries to sync this with the remote right away, but until the sync is complete, the data you see in Emacs is still the same that it was before you edited it. This gives the impression that you must wait for a sync to finish before it&apos;s complete and that Emacs is busy updating, when it actually isn&apos;t. I&apos;d love to see the Magit buffers update with your changes instantaneously, and then rather revert back (with an error message) if syncing with the remote failed.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Getting started&lt;/h2&gt;&lt;p&gt;To get started, I&apos;d recommend following &lt;a href=&quot;https://magit.vc/manual/forge/&quot;&gt;the manual&lt;/a&gt;, which outlines most of what you need to know and shows you all the keybindings you need. That said, I did run into some issues (both on macOS and on NixOS), and there was some prerequisite knowledge I did not have, so I&apos;ve decided to document that below.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Authentication: using &lt;code&gt;.authinfo&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;The manual does have a section on &lt;a href=&quot;https://magit.vc/manual/forge/Getting-Started.html#Getting-Started&quot;&gt;getting started&lt;/a&gt; that includes some writing on setting up authentication, but, at least for GitLab, it requires some steps not mentioned in the manual.&lt;/p&gt;&lt;p&gt;Emacs uses &lt;code&gt;~/.authinfo&lt;/code&gt; files to handle credentials. I struggled to find much information about the format and what is required, but I can confirm that this entry format works:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;machine gitlab.com/api/v4 login username^forge password api-token&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Simply replace &lt;code&gt;username&lt;/code&gt; and &lt;code&gt;api-token&lt;/code&gt; with your username and your API-token (with &apos;api&apos; scope), put it in &lt;code&gt;~/.authinfo&lt;/code&gt;, and you&apos;re off to the races. Admittedly, I don&apos;t know what the &lt;code&gt;^forge&lt;/code&gt; bit after the username means, but I assume it somehow relates it to Forge.&lt;/p&gt;&lt;p&gt;For more information on secrets and authentication, see &lt;a href=&quot;https://www.masteringemacs.org/article/keeping-secrets-in-emacs-gnupg-auth-sources&quot;&gt;this article on /Mastering Emacs/&lt;/a&gt;, which goes into quite a bit of detail of how to deal with encryption and credentials in Emacs.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;macOS issues&lt;/h3&gt;&lt;div class=&quot;section&quot;&gt;&lt;h4&gt;Can&apos;t fetch topics&lt;/h4&gt;&lt;p&gt;When setting it up on macOS, the biggest issue I ran into was that I couldn&apos;t successfully fetch topics (issues and pull requests). This appears to be a well-known bug with the &lt;code&gt;ghub&lt;/code&gt; package that Forge uses, and &lt;a href=&quot;https://github.com/magit/ghub/issues/81#issuecomment-598681924&quot;&gt;this GitHub issue&lt;/a&gt; has a couple of workarounds for it. Personally, I had to force a workaround, by evaluating the following snippet:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-emacs-lisp&quot;&gt;(setq ghub-use-workaround-for-emacs-bug &apos;force)&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;However, I didn&apos;t put it in my config, and it seems to have worked successfully without setting this on subsequent uses, so it may or may not be necessary.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h4&gt;Recursive load&lt;/h4&gt;&lt;p&gt;I also ran into a problem with &lt;code&gt;window-purpose&lt;/code&gt; during the setup, causing an error about &apos;recursive load&apos;. There is &lt;a href=&quot;https://github.com/bmag/emacs-purpose/issues/158&quot;&gt;an issue on GitHub&lt;/a&gt; that describes it. &lt;a href=&quot;https://github.com/bmag/emacs-purpose/issues/158#issuecomment-547293349&quot;&gt;One of the comments&lt;/a&gt; said to put&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-emacs-lisp&quot;&gt;(require &apos;window-purpose)&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;in your &lt;code&gt;.spacemacs&lt;/code&gt; file, which seemed to fix the issue for me.&lt;/p&gt;&lt;p&gt;This has not been an issue on NixOS.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;NixOS issues: &apos;no EmacSQL SQLite binary available&apos;&lt;/h3&gt;&lt;p&gt;NixOS required much less fiddling to get set up, but there was an issue with my Emacs missing a binary, causing it to fail on startup. Specifically, I was told that there was &apos;no EmacSQL SQLite binary available&apos;, much like &lt;a href=&quot;https://github.com/magit/forge/issues/84&quot;&gt;this issue about a missing C compiler&lt;/a&gt;. There may be a number of ways around it, but the solution I found was to change my installation of Emacs to one that includes the required &lt;code&gt;emacsql-sqlite&lt;/code&gt; package. To do that, I replaced my Emacs listing in &lt;code&gt;.configuration.nix&lt;/code&gt; with the following:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-nix&quot;&gt;(emacsWithPackages (epkgs: [ epkgs.emacsql-sqlite ]))&lt;/code&gt;&lt;/pre&gt;&lt;hr&gt;&lt;p&gt;I&apos;ve only just started using Forge, but I&apos;ve been very positively surprised by how much power it gives me directly from my favorite editor. Being able to check out and create branches from merge requests with a single command? &lt;strong&gt;Yes, please&lt;/strong&gt;. Not having to take my hands off the keyboard to set issue labels? &lt;strong&gt;Perfect&lt;/strong&gt;. Editing text and creating issues in an actual text editor and not having to copy it over into a browser window? &lt;strong&gt;You had me at Emacs&lt;/strong&gt;.&lt;/p&gt;&lt;p&gt;I suspect there is still much to discover, though, so let&apos;s get going!&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;/div&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Forge_(software)&quot;&gt;According to wikipedia&lt;/a&gt;, a &lt;i&gt;forge&lt;/i&gt; is &apos;a web-based collaborative software platform&apos;&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dl id=&quot;footnotes&quot;&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Forge_(software)&quot;&gt;According to wikipedia&lt;/a&gt;, a &lt;i&gt;forge&lt;/i&gt; is &apos;a web-based collaborative software platform&apos;&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;/dl&gt;</content:encoded></item><item><title><![CDATA[Org mode: tasty tricks]]></title><description><![CDATA[In which we explore some of the most useful features of Emacs' Org mode, including custom TODO keywords, the agenda view, and capture templates. Name-drops literate programming for bonus points.]]></description><link>https://blog.thomasheartman.com/posts/org-mode-tasty-tricks</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/org-mode-tasty-tricks</guid><pubDate>Mon, 09 Mar 2020 07:35:46 GMT</pubDate><content:encoded>&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Intro&lt;/h2&gt;&lt;p&gt;Org mode (&lt;a href=&quot;https://en.wikipedia.org/wiki/Org-mode&quot;&gt;Wikipedia&lt;/a&gt;, &lt;a href=&quot;https://orgmode.org/manual/Capture.html#Capture&quot;&gt;official website&lt;/a&gt;) is a powerful tool. On the surface, it looks like a lightweight markup language akin to Markdown, but if you look closer, you&apos;ll find that the Emacs major mode is &lt;i&gt;so&lt;/i&gt; much more. It&apos;s a scheduler, a task manager, a spreadsheet editor, an organizing tool, and a way to do &lt;i&gt;literate programming&lt;/i&gt;. I&apos;ve been using the basic functionality of Org for a long time, but I recently took some time to explore the manual and pick up some new tips and tricks.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Custom TODOs&lt;/h2&gt;&lt;p&gt;One of the easiest features to get started with is the TODO-system. Being able to tag a headline as &lt;code&gt;TODO&lt;/code&gt; or &lt;code&gt;DONE&lt;/code&gt; with a keypress makes it a super easy to get started with task management. I initially used it for logging work at my old job because keeping track of JIRA tickets through a web browser became a bit tedious.&lt;/p&gt;&lt;p&gt;The basic two-state system works well in a lot of cases, but sometimes you want a little more control. For that, you can create your own set of keywords. The paragraphs below give some examples of how I use it and some basic tips. For more information, consult &lt;a href=&quot;https://orgmode.org/manual/TODO-Items.html#TODO-Items&quot;&gt;the manual&lt;/a&gt;.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Creating and configuring keywords&lt;/h3&gt;&lt;p&gt;One simple, but very powerful feature of Org is that you can define your own set of keywords to use as TODO-states. You can do this on a global level or on the file level. While doing it on the &lt;i&gt;global level&lt;/i&gt; might be useful if you always want access to a specific set of keywords, defining your keywords at the &lt;i&gt;file level&lt;/i&gt; allows you to work with a custom set of keywords for every file you operate on.&lt;/p&gt;&lt;p&gt;To define keywords for a file, use the &lt;code&gt;#+TODO:&lt;/code&gt; keyword and list your desired states, using &lt;code&gt;|&lt;/code&gt; as a separator between states that need work and states that that are considered closed. For instance, here&apos;s the set of keywords that I&apos;m using for writing this very post. The set indicates whether a heading needs more work, is ready to be reviewed, is done, or if it should be cut:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-org&quot;&gt;#+TODO: TODO REVIEW | DONE CUT&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Emacs offers you a number of ways to switch the state of an item. By default &lt;code&gt;C-c C-t&lt;/code&gt; cycles through the list. You can also use &lt;code&gt;S-&amp;#x3C;right&gt;&lt;/code&gt; and &lt;code&gt;S-&amp;#x3C;left&gt;&lt;/code&gt; (that&apos;s &lt;code&gt;S&lt;/code&gt; as in &lt;code&gt;super&lt;/code&gt;), to change to the previous and next states, respectively.&lt;/p&gt;&lt;p&gt;When you have more than two states, switching to a specific state can start to get tricky if the flow isn&apos;t necessarily unidirectional. To make it easier to jump to a state, Org also allows you to add a &apos;hotkey&apos; that you can use to set that state. This is done by putting the desired key in parentheses after the keyword:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-org&quot;&gt;#+TODO: TODO(t) REVIEW(r) | DONE(d) CUT(c)&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now, when you invoke the &lt;code&gt;org-todo&lt;/code&gt; command (&lt;code&gt;C-c C-t&lt;/code&gt;), rather than cycling through states, Emacs asks you to enter one of the assigned keys. Thus, if an item is currently marked as TODO, but you want to move it to REVIEW, the whole command would be &lt;code&gt;C-c C-t r&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;If you want more information assigned to each state, you can also tell Org to log the date and time of when a TODO-state was assigned as well as prompt you to add a note when that happens. As an example, here&apos;s the setup I&apos;m experimenting with for recording and tracking blog post ideas:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-org&quot;&gt;#+TODO: IDEA(i!) DRAFT(d!) UPDATE(u@) READY(r!) | PUBLISHED(p!) ONHOLD(o@)&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;!&lt;/code&gt; after a letter tells Org mode to log the time when this state was entered. The &lt;code&gt;@&lt;/code&gt; tells Org mode that in addition to logging the time, I also want it to prompt me for a little note. With the set above, I want to track the times of all state changes, and when setting the state to &lt;code&gt;UPDATE&lt;/code&gt; or &lt;code&gt;ONHOLD&lt;/code&gt;, I also want to log a little note. This helps me remember why I put it in that state: Was there a paragraph that needed rephrasing? Have I got a better way to do things that I want to update a post with? Did I no longer see the post as relevant?&lt;/p&gt;&lt;p&gt;The ability to log all of these details is great, but it can quickly get messy. For instance, here&apos;s what a heading might end up looking like if we add some timestamps and notes to it:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-org&quot;&gt;** CUT Drawers
- State &quot;CUT&quot;        from &quot;REVIEW&quot;     [2020-03-08 Sun 20:17] \\
This is out of scope for now. Consider extracting this into a separate post.
- State &quot;REVIEW&quot;     from &quot;TODO&quot;       [2020-03-08 Sun 20:16]&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This can add up fast, so we can make use of what Org calls &lt;i&gt;drawers&lt;/i&gt; to keep our file tidy. These are delimited blocks of content that can contain anything but headlines and other drawers. Content put into drawers will be hidden by default (Org collapses it for you), and it will not be expanded by regular visibility cycling. If you want to cycle the visibility of a drawer, place your cursor on the drawer to cycle it.&lt;/p&gt;&lt;p&gt;Logging to a drawer would change the above example to this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-org&quot;&gt;** CUT Drawers
:LOGBOOK:
- State &quot;CUT&quot;        from &quot;REVIEW&quot;     [2020-03-08 Sun 20:17] \\
This is out of scope for now. Consider extracting this into a separate post.
- State &quot;REVIEW&quot;     from &quot;TODO&quot;       [2020-03-08 Sun 20:16]
:END:&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now, no matter how many more entries you add to the log, Org will just show you a collapsed &lt;code&gt;:LOGBOOK:&lt;/code&gt; line (that you can expand if you want to). To make Org log into drawers, use the following line:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-org&quot;&gt;#+PROPERTY: LOG_INTO_DRAWER t&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Org-agenda&lt;/h2&gt;&lt;p&gt;Another part of Org that has great synergy with TODO-items is the agenda view. To get started with agenda, you can add a file to the agenda list with &lt;code&gt;org-agenda-file-to-front&lt;/code&gt; (&lt;code&gt;C-c [&lt;/code&gt;). Then, when you invoke Org Agenda, you can choose between a number of different ways to view data found in all your agenda list files.&lt;/p&gt;&lt;p&gt;I&apos;m still getting into it, but I&apos;ve found immediate benefit from being able to quickly get an overview of all my open TODO items, and being able to easily toggle their states from a unified view, no matter which file they&apos;re located in.&lt;/p&gt;&lt;p&gt;For more information, see &lt;a href=&quot;https://orgmode.org/manual/Agenda-Views.html#Agenda-Views&quot;&gt;the chapter on agenda views in the Org Mode manual&lt;/a&gt;.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Org capture templates&lt;/h2&gt;&lt;p&gt;Capture templates allow you to quickly and easily record notes and ideas into predefined files using a format you specify yourself. This is great for when you get little ideas that you just need to jot down somewhere and store for later.&lt;/p&gt;&lt;p&gt;I use it to record post ideas and to track the state of certain processes at work. The template allows you to automatically add plenty of context and to prompt the user for specific keywords, making the recording process as painless as you want to. Again, the &lt;a href=&quot;https://orgmode.org/manual/Capture.html#Capture&quot;&gt;manual is the best place to go&lt;/a&gt; for more information.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Literate programming&lt;/h2&gt;&lt;p&gt;One aspect of Org mode that I&apos;m really excited about but haven&apos;t really gotten into yet is &lt;a href=&quot;https://en.wikipedia.org/wiki/Literate_programming&quot;&gt;/literate programming/&lt;/a&gt;. In short, literate programming is a way of intermingling source code blocks and natural language to be able to express intent and explain choices taken along the way.&lt;/p&gt;&lt;p&gt;There is some documentation on it &lt;a href=&quot;https://orgmode.org/worg/org-contrib/babel/intro.html#literate-programming&quot;&gt;on the org mode website&lt;/a&gt;, and I have done some very limited experiments with &lt;i&gt;tangling&lt;/i&gt; and &lt;i&gt;weaving&lt;/i&gt;. Writing an Emacs config from the ground up should be a perfect use case for it, as should any upcoming posts that contain code examples that can be compiled into a standalone program.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Closing thoughts&lt;/h2&gt;&lt;p&gt;This is just scratching the surface of what Org mode can do. There is so much I haven&apos;t covered here, including working with tables, org-babel, tags, exporting files, and so forth; but even with just this, Org mode is already a force to be reckoned with.&lt;/p&gt;&lt;p&gt;I can see a bright future where my life is nothing but plain text. 🦄&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Nix: override packages with overlays]]></title><description><![CDATA[In which we take a first look at Nix overlays, a mechanism which allows you to override and modify the package sets, and at how we can use that to get more up-to-date versions of our tools.]]></description><link>https://blog.thomasheartman.com/posts/nix-override-packages-with-overlays</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/nix-override-packages-with-overlays</guid><pubDate>Mon, 02 Mar 2020 08:26:30 GMT</pubDate><content:encoded>&lt;p&gt;In general, I am exceedingly happy with the &lt;a href=&quot;https://discourse.nixos.org/t/how-to-install-github-released-binary/1328/3&quot;&gt;Nix package manager&lt;/a&gt;, but one issue that I occasionally run into is that some packages aren&apos;t quite up to date. Usually, this isn&apos;t a big deal, and I&apos;ve just had to learn that I can&apos;t always live on the bleeding edge. However, when you require functionality that was introduced after the Nix package was last updated, you&apos;re suddenly out of luck.&lt;/p&gt;&lt;p&gt;Luckily, though, Nix provides something called &lt;i&gt;overlays&lt;/i&gt;, which you can use &quot;to extend and change nixpkgs&quot; according to the &lt;a href=&quot;https://nixos.wiki/wiki/Overlays&quot;&gt;NixOS documentation&lt;/a&gt;.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;A brief summary of the problem&lt;/h2&gt;&lt;p&gt;To make this easier to follow, I&apos;ll make the problem more concrete. One of my goals for myself when working with Kubernetes, is to have absolutely all configuration stored as code. Regardless of how you feel about YAML, there&apos;s no denying that it can easily get tedious and repetitive with no templating or programming language features baked in.&lt;/p&gt;&lt;p&gt;For a while now, I&apos;ve been wanting to look into the &lt;a href=&quot;https://dhall-lang.org/&quot;&gt;Dhall language&lt;/a&gt; for configuration, and this seemed a perfect opportunity, considering it also has &lt;a href=&quot;https://github.com/dhall-lang/dhall-kubernetes&quot;&gt;Kubernetes bindings&lt;/a&gt;. But here&apos;s the problem: the Dhall version in nixpkgs is &lt;code&gt;1.24.0&lt;/code&gt;, but the Kubernetes bindings require at least &lt;code&gt;1.27.0&lt;/code&gt; to work.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;What are overlays?&lt;/h2&gt;&lt;p&gt;For a more thorough explanation, consult the &lt;a href=&quot;https://nixos.wiki/wiki/Overlays&quot;&gt;NixOS wiki&lt;/a&gt; or watch &lt;a href=&quot;https://youtu.be/W85mF1zWA2o&quot;&gt;/Nixpkgs Overlays --- A place for all excluded packages/ by Nicolas Pierron&lt;/a&gt;. In short, overlays are functions that transform package sets by adding or overriding keys. Notably, Mozilla has their own set of Nix packages, &lt;a href=&quot;https://github.com/mozilla/nixpkgs-mozilla&quot;&gt;Mozilla nixpkgs&lt;/a&gt;, which contains a Rust overlay, allowing Nix users to stay up to date with the quick cadence of Rust releases. In our case, it allows us to replace the packages that are out of date with newer updated versions.&lt;/p&gt;&lt;p&gt;There&apos;s quite a bit of content out there on how to use overlays: the aforementioned resources are a great place to start, and blog posts like &lt;a href=&quot;https://blog.flyingcircus.io/2017/11/07/nixos-the-dos-and-donts-of-nixpkgs-overlays/&quot;&gt;the DOs and DON&apos;Ts of overlays by Flying Circus&lt;/a&gt; offer further insights. That said, I couldn&apos;t find anything that really fit my use case. Thankfully, the helpful people over at the &lt;a href=&quot;https://discourse.nixos.org/t/how-to-use-packages-from-different-channels-in-nix-shells/6055/3&quot;&gt;NixOS Discourse forums&lt;/a&gt; &lt;a href=&quot;https://discourse.nixos.org/t/how-to-use-packages-from-different-channels-in-nix-shells/6055/3&quot;&gt;pointed me in the right direction&lt;/a&gt;.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The solution&lt;/h2&gt;&lt;p&gt;Now that we know what they are and how they work, we can take a stab at creating our own overlays.&lt;/p&gt;&lt;p&gt;Let&apos;s assume our folder structure looks like the following:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;├── shell.nix
└── nix-files
    └── overlay.nix&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can then write a very simple &lt;code&gt;shell.nix&lt;/code&gt; file that just sets us up with the &lt;code&gt;dhall&lt;/code&gt; package.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-nix&quot;&gt;{ pkgs ? &lt;span class=&quot;hljs-built_in&quot;&gt;import&lt;/span&gt; &amp;#x3C;nixpkgs&gt; { &lt;span class=&quot;hljs-attr&quot;&gt;overlays&lt;/span&gt; = [ (&lt;span class=&quot;hljs-built_in&quot;&gt;import&lt;/span&gt; ./nix-files/overlay.nix) ]; }
}:
stdenv.mkDerivation {
  &lt;span class=&quot;hljs-attr&quot;&gt;name&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;dhall&quot;&lt;/span&gt;;
  &lt;span class=&quot;hljs-attr&quot;&gt;buildInputs&lt;/span&gt; = [ pkgs.dhall ];
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;There&apos;s nothing terribly exciting going on here, but notice that when importing &lt;code&gt;nixpkgs&lt;/code&gt;, we specify a list of overlays. In our case, it&apos;s only one, but we can use as many as we want.&lt;/p&gt;&lt;p&gt;With this all set up, let&apos;s have a look at the overlay:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-nix&quot;&gt;self: super: {
  &lt;span class=&quot;hljs-attr&quot;&gt;dhall&lt;/span&gt; = &lt;span class=&quot;hljs-built_in&quot;&gt;builtins&lt;/span&gt;.fetchTarball
    &lt;span class=&quot;hljs-string&quot;&gt;&quot;https://github.com/dhall-lang/dhall-haskell/releases/download/1.30.0/dhall-1.30.0-x86_64-linux.tar.bz2&quot;&lt;/span&gt;;
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The first line lists the expression&apos;s parameters. By convention, they&apos;re called &lt;code&gt;self&lt;/code&gt; and &lt;code&gt;super&lt;/code&gt;. In our case, we needn&apos;t concern ourselves with them, because we&apos;re replacing one of the keys entirely. The actual value of the expression is just a set with a single key, &lt;code&gt;dhall&lt;/code&gt;, mapped to the result of fetching a tarball. This replaces that value in the original package set.&lt;/p&gt;&lt;p&gt;Some additional notes on the overlay: We&apos;re using the plain version of the &lt;code&gt;builtins.fetchTarball&lt;/code&gt; function in this example. There&apos;s also a version that takes an attribute set with a URL and a hash, which will make sure that the you get the same version every time. Furthermore, we&apos;re specifying which exact version we want (&lt;code&gt;1.30.0&lt;/code&gt;). That&apos;s perfectly fine for a little example like this, and will probably be good enough for a little dev environment. It would be ideal, though, if we could make sure we&apos;re always up to date with the latest release. The aforementioned &lt;a href=&quot;https://discourse.nixos.org/t/how-to-use-packages-from-different-channels-in-nix-shells/6055/3&quot;&gt;forum help thread&lt;/a&gt; has a suggestion for how to do this, but it seemed to have some unexpected issues, so I’ll leave that as an exercise for the reader.&lt;/p&gt;&lt;p&gt;Now, when loading the &lt;code&gt;shell.nix&lt;/code&gt; file, we should see the following:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;$ dhall version
1.30.0&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Boom.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Kubernetes first steps]]></title><description><![CDATA[In which provision my first managed Kubernetes cluster and suddenly find myself without any idea of what to do next. More navel gazing than usual, this post is largely about trying to find out what I want to do with this beast of a system.]]></description><link>https://blog.thomasheartman.com/posts/kubernetes-first-steps</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/kubernetes-first-steps</guid><pubDate>Sun, 23 Feb 2020 20:20:58 GMT</pubDate><content:encoded>&lt;p&gt;One of my stated &lt;a href=&quot;https://blog.thomasheartman.com/posts/goodbye-2019-hello-2020/&quot;&gt;goals for this year&lt;/a&gt;, was to have a Kubernetes cluster running &lt;i&gt;somewhere&lt;/i&gt;. As stated in the goals post, the deadline for this was April 1^{st}. As of Saturday night, I&apos;ve got one.&lt;/p&gt;&lt;p&gt;I ended up using &lt;a href=&quot;https://www.digitalocean.com/&quot;&gt;Digital Ocean&lt;/a&gt; for this, taking advantage of the &lt;a href=&quot;https://changelog.com/podcast&quot;&gt;Changelog podcast&apos;s&lt;/a&gt; &lt;a href=&quot;https://do.co/changelog&quot;&gt;sponsored signup offer&lt;/a&gt;, giving  me two months to spend a $100 credit. While I&apos;ve heard a lot of good things about Digital Ocean being very affordable, their managed Kubernetes offering can easily rack up some costs if you don&apos;t take care.&lt;/p&gt;&lt;p&gt;But now that I&apos;ve got the cluster up and running, I&apos;m at a bit of a loss. Just where do I go from here? What&apos;s the next thing to do? What should I prioritize? And why didn&apos;t I just start off with Minikube?&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Why didn&apos;t I just use Minikube for now?&lt;/h2&gt;&lt;p&gt;Actually, let&apos;s start with the last question: Why didn&apos;t I just use Minikube? Honestly, it was mostly a moment of weakness. I was actually busy procrastinating when I thought, &apos;hmm, I wonder how long it&apos;d take to get set up with Digital Ocean&apos;.&lt;/p&gt;&lt;p&gt;In hindsight: sure, Minikube would have been cheaper (at least once my credit is up), but having the actual cluster feels more &apos;real&apos;. Like it&apos;s something I need to take care of. It&apos;s also available from anywhere and doesn&apos;t use my machine&apos;s processing power.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;What do I want to get out of this?&lt;/h2&gt;&lt;p&gt;So I got the cluster. Now what? Well, &lt;i&gt;why&lt;/i&gt; did I want to do this?&lt;/p&gt;&lt;p&gt;While the option to just spawn little demo applications and have them available from wherever  is great, I&apos;m more interested in looking at Kubernetes for the overarching architecture and operational side of things. Specifically, I&apos;d like to use this as a way to familiarize myself with:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;service meshes and API gateways&lt;/li&gt;&lt;li&gt;monitoring and telemetry&lt;/li&gt;&lt;li&gt;security best practices&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Each of these topics require a great deal of time and practice to master, but I&apos;m not expecting to be a wizened monk any time soon. These are areas that I find fascinating and that I want to explore, but I cannot yet lay out any specific goals, as I need more time to research them.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Wait, didn&apos;t I have another goal for Kubernetes?&lt;/h2&gt;&lt;p&gt;Sure did! In addition to just getting a cluster ready, my second Kubernetes goal was to expose a Haskell app with an API. This is still on the cards, but isn&apos;t due any time soon. This leans more towards the Nix and Haskell side of things, and less directly towards Kubernetes, so I can take some time to figure out how I want to do it.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Now what?&lt;/h2&gt;&lt;p&gt;So where does this leave me? I think the biggest issue I have identified is my lack of knowledge. I&apos;ve been working with RedHat&apos;s OpenShift for the past year, and feel like I have a pretty good grasp of how that works, at least from the dev side. But when faced with that clean cluster, I froze. I didn&apos;t know where to go, didn&apos;t know what commands to run, or where to turn to for advice. So I need to formulate a plan.&lt;/p&gt;&lt;p&gt;I think I would like to familiarize myself with Kubernetes more or less from the ground up. That means reading documentation, doing tutorials, and making sure my understanding is correct. Second: I would like to have a look at basic security measures and best practices. At the very least, I want to enable and configure &lt;a href=&quot;https://kubernetes.io/docs/reference/access-authn-authz/rbac/&quot;&gt;RBAC&lt;/a&gt;. When I get this far, I think it would be an appropriate time to take a step back and reevaluate where I&apos;m headed and recalculate.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Corecursion and anamorphisms]]></title><description><![CDATA[In which we explore the concepts of corecursion and anamorphisms. We look at what corecursion and anamorphisms are, relate them back to recursion and catamorphisms, and then have some fun with exploring different ways unfold numbers into different representations.]]></description><link>https://blog.thomasheartman.com/posts/corecursion-and-anamorphisms</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/corecursion-and-anamorphisms</guid><pubDate>Mon, 17 Feb 2020 06:37:13 GMT</pubDate><content:encoded>&lt;p&gt;You know that feeling where you hear about something and you immediately need to look into it? I had that while listening to &lt;a href=&quot;https://corecursive.com/046-don-and-adam-folds/&quot;&gt;the most recent episode of Adam Gordon Bell&apos;s /Corecursive/ podcast&lt;/a&gt; today, where they were talking about where the name of the podcast came from. Up until then I had just assumed that &lt;i&gt;corecursive&lt;/i&gt; meant /mutually recursive/&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;, but boy, was I wrong!&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The C-word&lt;/h2&gt;&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Corecursion&quot;&gt;According to Wikipedia&lt;/a&gt;, &apos;&lt;i&gt;corecursion&lt;/i&gt; is type of operation that is a &lt;a href=&quot;https://en.wikipedia.org/wiki/Dual_(category_theory)&quot;&gt;dual&lt;/a&gt; to recursion&apos;. This quickly gets very theoretical, but the long and short of it is that corecursion can be seen as a kind of opposite of recursion: Where recursion allows you to operate on arbitrarily complex data as long as you can reduce it down to a set of base cases, corecursion allows you to generate arbitrarily complex data when given a base case.&lt;/p&gt;&lt;p&gt;&lt;i&gt;Err ... what?&lt;/i&gt;&lt;/p&gt;&lt;p&gt;Think of it like this: Given a list of numbers (arbitrarily complex data), you can define a recursive function to sum all the numbers using simple base cases: is the list empty or are there more elements to add? Your language of choice may well have a &lt;code&gt;sum&lt;/code&gt; function that does just this. If not, you can implement it with a &lt;code&gt;fold&lt;/code&gt; or &lt;code&gt;reduce&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;However, given a number, can you create a list that when summed up would equal this number? This would be a form of corecursion, where we take simple data (a number), and generate arbitrarily complex data based on the input (the resulting list of numbers).&lt;/p&gt;&lt;p&gt;Let&apos;s talk about &lt;code&gt;fold&lt;/code&gt; functions specifically. As we talked about in a &lt;a href=&quot;https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-x/&quot;&gt;previous post on folding&lt;/a&gt;, &lt;code&gt;fold&lt;/code&gt; functions are &lt;i&gt;catamorphisms&lt;/i&gt;. They take a data structure and reduce it to a &apos;lower&apos; form. The opposite of a catamorphism is an /anamorphism/&lt;sup id=&quot;fnr-2&quot; class=&quot;footnote-ref&quot; data-label=&quot;2&quot;&gt;&lt;a href=&quot;#fn-2&quot;&gt;[2]&lt;/a&gt;&lt;/sup&gt;, and the opposite of a &lt;code&gt;fold&lt;/code&gt; is an &lt;code&gt;unfold&lt;/code&gt; (at least in Haskell). An anamorphism generates a sequence by repeatedly applying a function onto its previous result.&lt;/p&gt;&lt;p&gt;According to Wikipedia, &apos;&lt;a href=&quot;https://www.wikiwand.com/en/Anamorphism&quot;&gt;the anamorphism of a coinductive type denotes the assignment of a coalgebra to its unique morphism to the final coalgebra of an endofunctor.&lt;/a&gt;&apos; Don&apos;t worry: you needn&apos;t understand that to understand unfolding and corecursion (I sure don&apos;t). Instead, let&apos;s try and get a feel of what we might use corecursion for.&lt;/p&gt;&lt;p&gt;Returning to our previous example of destructuring a number into a list of terms, let&apos;s look at a couple of ways to do it using unfold.&lt;/p&gt;&lt;p&gt;First, let&apos;s look at  the &lt;code&gt;unfoldr&lt;/code&gt; function itself. It is defined in the &lt;code&gt;Data.List&lt;/code&gt; module, and its type signature is:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;unfoldr&lt;/span&gt; :: (b -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Maybe&lt;/span&gt; (a, b)) -&gt; b -&gt; [a]&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Given a function from &lt;code&gt;b&lt;/code&gt; to &lt;code&gt;Maybe (a, b)&lt;/code&gt; and a &lt;code&gt;b&lt;/code&gt;, it will produce a list of &lt;code&gt;a&lt;/code&gt;. If the function (let&apos;s call it &lt;code&gt;f&lt;/code&gt;) returns &lt;code&gt;Just (x, y)&lt;/code&gt;, &lt;code&gt;x&lt;/code&gt; will be added to the result, and &lt;code&gt;f&lt;/code&gt; will be called again with &lt;code&gt;y&lt;/code&gt;. This continues until &lt;code&gt;f&lt;/code&gt; returns &lt;code&gt;Nothing&lt;/code&gt;, at which point &lt;code&gt;unfoldr&lt;/code&gt; terminates, returning the list it has created.&lt;/p&gt;&lt;p&gt;With this, we can create a function that takes an integral value and returns a list that when summed, is equal to the value we passed in. We&apos;ll start with an easy variant that just destructures the input into ones. For simplicity&apos;s sake, we&apos;re ignoring negative numbers.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;module&lt;/span&gt; Unfold &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;

&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; Data.List (&lt;span class=&quot;hljs-title&quot;&gt;unfoldr&lt;/span&gt;)

&lt;span class=&quot;hljs-title&quot;&gt;unroll&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;Integral&lt;/span&gt; a =&gt; a -&gt; [a]
&lt;span class=&quot;hljs-title&quot;&gt;unroll&lt;/span&gt; = unfoldr f
  &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;
    f n
      | n &amp;#x3C;= &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;Nothing&lt;/span&gt;
      | otherwise = &lt;span class=&quot;hljs-type&quot;&gt;Just&lt;/span&gt; (&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;, n - &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;)&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Easy enough. The function passed to &lt;code&gt;unfoldr&lt;/code&gt; returns nothing if there is no more to sum. Otherwise, add $1$ to the list, and call again with &lt;code&gt;n-1&lt;/code&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;unroll&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;hljs-comment&quot;&gt;-- [1,1,1,1,1]&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;unroll&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;hljs-comment&quot;&gt;-- []&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;But we can have some more fun with this. How about we try and destructure a number into a list of the pieces we&apos;d need to create a binary representation of it?&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;binary&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;Integral&lt;/span&gt; a =&gt; a -&gt; [a]
&lt;span class=&quot;hljs-title&quot;&gt;binary&lt;/span&gt; = unfoldr f
  &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;
    f n
      | n &amp;#x3C;= &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;Nothing&lt;/span&gt;
      | otherwise =
        &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; powerOfTwo = &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; ^ floor (logBase &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; $ fromIntegral n)
         &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Just&lt;/span&gt; (powerOfTwo, n - powerOfTwo)&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This is a bit more complicated, but only because we need to map the input value to a power of two. Luckily, we can use &lt;code&gt;logBase 2&lt;/code&gt; to get the exponent you&apos;d need to get &lt;code&gt;n&lt;/code&gt;, and then &lt;code&gt;floor&lt;/code&gt; it to get the greatest integral exponent. This becomes the next entry to the list. What&apos;s left gets passed in to the next application of the function.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;binary&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;hljs-comment&quot;&gt;-- []&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;binary&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;hljs-comment&quot;&gt;-- [4,1]&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;binary&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;255&lt;/span&gt; &lt;span class=&quot;hljs-comment&quot;&gt;-- [128,64,32,16,8,4,2,1]&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;binary&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;256&lt;/span&gt; &lt;span class=&quot;hljs-comment&quot;&gt;-- [256]&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Pretty neat, huh? What if we take it a step further and convert the number to its binary representation instead, as if it was base 2?&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;base2&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;Integral&lt;/span&gt; a =&gt; a -&gt; a
&lt;span class=&quot;hljs-title&quot;&gt;base2&lt;/span&gt; = sum . unfoldr f
  &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;
    f n
      | n &amp;#x3C;= &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;Nothing&lt;/span&gt;
      | otherwise =
        &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; exponent = floor (logBase &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; $ fromIntegral n)
         &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Just&lt;/span&gt; (&lt;span class=&quot;hljs-number&quot;&gt;10&lt;/span&gt; ^ exponent, n - &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; ^ exponent)&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As you&apos;d expect:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;base2&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;hljs-comment&quot;&gt;-- 0&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;base2&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;hljs-comment&quot;&gt;-- 101&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;base2&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;hljs-comment&quot;&gt;-- 1010&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Not too shabby at all.&lt;/p&gt;&lt;hr&gt;&lt;p&gt;Alright, I think we have had enough fun with corecursion for now. It&apos;s been a very unexpected, but very insightful little journey, and I thank you for taking it with me. Until next time!&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;/div&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;I&apos;m probably not the only one to do this. Wikipedia has a note under disambiguation on its article on corecursion that says &apos;not to be confused with mutual recursion&apos;&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[2]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-2&quot; class=&quot;footnote&quot; data-label=&quot;2&quot;&gt;&lt;p&gt;Similar to how your body can be in either anabolic or catabolic states, for all you fitness people out there.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dl id=&quot;footnotes&quot;&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;I&apos;m probably not the only one to do this. Wikipedia has a note under disambiguation on its article on corecursion that says &apos;not to be confused with mutual recursion&apos;&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[2]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-2&quot; class=&quot;footnote&quot; data-label=&quot;2&quot;&gt;&lt;p&gt;Similar to how your body can be in either anabolic or catabolic states, for all you fitness people out there.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;/dl&gt;</content:encoded></item><item><title><![CDATA[My first Emacs Lisp]]></title><description><![CDATA[In which I heed Reddit's advice and write my first set of Emacs Lisp functions to customize Emacs. Turns out it's not all black magic and witches' brew! In addition to looking at why I wrote the functions, we'll be analyzing what the different bits mean.]]></description><link>https://blog.thomasheartman.com/posts/my-first-emacs-lisp</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/my-first-emacs-lisp</guid><pubDate>Mon, 10 Feb 2020 08:04:46 GMT</pubDate><content:encoded>&lt;p&gt;In &lt;a href=&quot;https://blog.thomasheartman.com/posts/tips-and-tricks-for-the-fledgling-emacs-user/&quot;&gt;my previous post on reading the Emacs manual&lt;/a&gt;, I mentioned that there were a couple of things that I was missing from my editing workflow when using regular Emacs bindings. The most notable of which was the ability to kill up until a search hit. I knew that it&apos;d be possible to write a function to do it, but I didn&apos;t really know where to start, so I figured I&apos;d just do it later.&lt;/p&gt;&lt;p&gt;In the &lt;a href=&quot;https://www.reddit.com/r/emacs/comments/eycyp2/blog_post_tips_and_tricks_from_the_manual/&quot;&gt;Reddit thread&lt;/a&gt; about the post, user &lt;a href=&quot;https://www.reddit.com/user/e17i/&quot;&gt;e17i&lt;/a&gt; gave me a little snippet to get me started for writing such a function. Turns out that was all I needed to get started. I put aside my fear of Lisp and went to work.&lt;/p&gt;&lt;p&gt;I ended up with three functions for Vim-like search movement: just exiting a search at a result, killing up to a search result, and copying up to a search result. Not particularly complicated, but I was &lt;i&gt;so&lt;/i&gt; proud of myself when I got it working.  The functions are included below for your viewing pleasure&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-emacs-lisp&quot;&gt;(defun isearch-vim-style-exit ()
  &quot;Move point to the start of the matched string, regardless
  of search direction.&quot;
  (interactive)
  (when (eq isearch-forward t)
    (goto-char isearch-other-end))
  (isearch-exit))

(defun isearch-vim-style-kill ()
  &quot;Kill up to the search match when searching forward. When
searching backward, kill to the beginning of the match.&quot;
  (interactive)
  (isearch-vim-style-exit)
  (call-interactively &apos;kill-region))

(defun isearch-vim-style-copy ()
  &quot;Copy up to the search match when searching forward. When
  searching backward, copy to the start of the search match.&quot;
  (interactive)
  (isearch-vim-style-exit)
  (call-interactively &apos;kill-ring-save)
  (exchange-point-and-mark))&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;I&apos;ve mapped the functions to three separate key bindings in &lt;code&gt;isearch-mode-map&lt;/code&gt; to make them easily accessible while searching:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-emacs-lisp&quot;&gt;(define-key isearch-mode-map
  (kbd &quot;&amp;#x3C;C-return&gt;&quot;) &apos;isearch-vim-style-exit)

(define-key isearch-mode-map
  (kbd &quot;&amp;#x3C;M-return&gt;&quot;) &apos;isearch-vim-style-kill)

(define-key isearch-mode-map
  (kbd &quot;&amp;#x3C;C-M-return&gt;&quot;) &apos;isearch-vim-style-copy)&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Justification and motivation&lt;/h2&gt;&lt;p&gt;In Emacs, when searching with &lt;code&gt;isearch&lt;/code&gt;, when you &apos;accept&apos; a match and move point there, Emacs will put you at the end of your matched text. Sometimes this is exactly what you want. Often, though, I find that I&apos;d rather have point move to just before where the search string matches. This is how it works in Vim, and I have convinced myself that it&apos;s also the standard way of moving cursors to searches in other text editors. In addition to just &lt;i&gt;moving&lt;/i&gt; to a search result, I want the same pattern to apply for &lt;i&gt;killing&lt;/i&gt; and for &lt;i&gt;copying&lt;/i&gt; the text between your original cursor position and the search match. In short, these functions act on everything between your original cursor position and the start of the selected match, regardless of whether you search forwards or backwards.&lt;/p&gt;&lt;p&gt;This functionality is the same as regular isearch when searching backward, but when searching forward it&apos;s the same as adding an extra &lt;code&gt;C-r&lt;/code&gt; (&lt;code&gt;isearch-backward&lt;/code&gt;) after picking a match.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The Reddit snippet&lt;/h2&gt;&lt;p&gt;The tip I got on Reddit gave me a little code snippet to start me off. At first I thought it was just what I wanted, but I realized later that it wasn&apos;t quite what I was looking for. The original snippet is very symmetrical in that it goes to the end of a match when searching backward and to the start of a match when searching forward. However, I have found that I always want to move to the start of a match, no matter what side I come at it from. This may seem asymmetrical, but one nice thing about it is that it&apos;ll work the same on any match, regardless of whether you&apos;re searching forward or backward. This is especially useful if your search has wrapped.&lt;/p&gt;&lt;p&gt;The original snippet was:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-emacs-lisp&quot;&gt;(define-key isearch-mode-map (kbd &quot;&amp;#x3C;C-return&gt;&quot;)
  (lambda () (interactive)
    (isearch-repeat(if (eq isearch-forward nil)
                      &apos;forward
                    &apos;backward))
    (isearch-exit)))&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So even if it wasn&apos;t quite what I needed, it gave me the tools necessary to start working on my own implementation, namely the &lt;code&gt;isearch-repeat&lt;/code&gt; and &lt;code&gt;isearch-exit&lt;/code&gt; functions and the &lt;code&gt;isearch-forward&lt;/code&gt; variable. With this I had all I needed to start playing around with the functionality myself.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Elisp crash course&lt;/h2&gt;&lt;p&gt;If you&apos;ve never encountered Lisp before, here&apos;s a short (and very incomplete) introduction to Emacs Lisp. Do bear in mind that this &lt;i&gt;is&lt;/i&gt; the first Emacs Lisp code I&apos;ve written myself, so I&apos;m probably missing a lot of context and nuance. If you find any errors, please do tell me; I&apos;ll be very grateful. For a more complete introduction to the language, check out the &lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/elisp/index.html&quot;&gt;Emacs Lisp manual&lt;/a&gt;.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;code&gt;defun&lt;/code&gt; [name] (args) ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;The first line of the function contains the keyword &lt;code&gt;defun&lt;/code&gt;, signifying that we&apos;re defining a function, the name of the function, and a list of parameters. In all the above functions, the parameter list is empty, so it&apos;s just a set of empty parentheses (&lt;code&gt;()&lt;/code&gt;).&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Comments ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;After the first line of each function, I&apos;ve added a string describing what the function does. This works as documentation. When looking up the function in Emacs (&lt;code&gt;C-h f &amp;#x3C;name of function&gt;&lt;/code&gt;), this text gets displayed. It&apos;s not a requirement to put into a function, but it&apos;s nice to have when you need to look things up.&lt;/p&gt;&lt;p&gt;Furthermore, lines starting with &lt;code&gt;;&lt;/code&gt; are standard code comments, such as the one about setting &lt;code&gt;current~prefix-arg&lt;/code&gt;.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;code&gt;(interactive)&lt;/code&gt; and &lt;code&gt;call-interactively&lt;/code&gt; ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;In Emacs Lisp, &lt;code&gt;(interactive)&lt;/code&gt; turns a Lisp function into a &lt;i&gt;command&lt;/i&gt;. In short, this means that you can assign it to a key sequence and call it from anywhere in Emacs by using &lt;code&gt;M-x&lt;/code&gt;. Similarly, &lt;code&gt;call-interactively&lt;/code&gt; is used to call interactive commands that take arguments. These commands can either be given explicit arguments and called like normal functions, or we can use &lt;code&gt;call-interactively&lt;/code&gt;. When doing the latter, certain parameters can be passed implicitly. For instance &lt;code&gt;kill-region&lt;/code&gt; needs two arguments &lt;code&gt;BEG&lt;/code&gt; and &lt;code&gt;END&lt;/code&gt; to know what region to operate on. When called interactively, &lt;code&gt;BEG&lt;/code&gt; and &lt;code&gt;END&lt;/code&gt; get the values of point and mark, so we don&apos;t need to pass them explicitly. For more information about the commands and &lt;code&gt;interactive&lt;/code&gt;, check out the &lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/elisp/Defining-Commands.html#Defining-Commands&quot;&gt;Emacs Lisp manual, chapter 21.2&lt;/a&gt;.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;What&apos;s with the quotes? ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Again, &lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/elisp/Quoting.html&quot;&gt;the manual (chapter 10.3)&lt;/a&gt; has info on what the single quotes do on a deeper level, but in our case, what we want is simply to pass the quoted &lt;i&gt;function&lt;/i&gt; as an argument, and not the &lt;i&gt;result&lt;/i&gt; of evaluating that function. In short, it&apos;s passing a function pointer, rather than the result of a function.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;code&gt;when&lt;/code&gt; ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;code&gt;when&lt;/code&gt; is the Lisp way to only evaluate some code &lt;i&gt;when&lt;/i&gt; a condition holds true. It&apos;s similar to an &lt;code&gt;if&lt;/code&gt; expression, but an &lt;code&gt;if&lt;/code&gt; expression needs an else-clause to run if the provided condition &lt;i&gt;doesn&apos;t&lt;/i&gt; hold true. In languages like Python, Rust, JavaScript, etc., it&apos;s the equivalent of just using an &lt;code&gt;if&lt;/code&gt; expression/statement without an &lt;code&gt;else&lt;/code&gt;-clause.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;code&gt;let&lt;/code&gt; and &lt;code&gt;current-prefix-arg&lt;/code&gt; ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;There&apos;s not a whole lot of variable binding going on in these functions. The one place it&apos;s done is in the &lt;code&gt;isearch-vim-style-copy&lt;/code&gt; function. As you might expect, the &lt;code&gt;let&lt;/code&gt; keyword assigns a value to a variable (in this case &lt;code&gt;(4)&lt;/code&gt; to &lt;code&gt;current-prefix-arg&lt;/code&gt;). In Emacs Lisp, variables can have global scope, so the &lt;code&gt;let&lt;/code&gt; binding ensures that the variable is only bound to this value within this scope. The variable &lt;code&gt;current-prefix-arg&lt;/code&gt; is used to augment &lt;code&gt;set-mark-command&lt;/code&gt;. We do this to move point back to where the search started after copying the region.&lt;/p&gt;&lt;hr&gt;&lt;p&gt;And that&apos;s the story of how I got started writing Lisp. It&apos;s dead simple, but I&apos;ve got a taste for it now, and I think I like it. ... yeah. I think I like it.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;/div&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;The code above has been modified from its original published state after &lt;a href=&quot;https://www.reddit.com/r/emacs/comments/f1x0jq/blog_post_my_first_emacs_lisp/&quot;&gt;feedback from Reddit&lt;/a&gt; and working with it some more. The original snippet looked like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-emacs-lisp&quot;&gt;(defun isearch-vim-style-exit ()
  &quot;Move point to the start of the matched string, regardless
    of search direction.&quot;
  (interactive)
  (when (eq isearch-forward t)
    (isearch-repeat &apos;backward))
  (isearch-exit))

(defun isearch-vim-style-kill ()
  &quot;Kill up to the search match when searching forward. When
    searching backward, kill to the beginning of the match.&quot;
  (interactive)
  (isearch-vim-style-exit)
  (call-interactively &apos;kill-region))

(defun isearch-vim-style-copy ()
  &quot;Copy up to the search match when searching forward. When
    searching backward, copy to the start of the search match.&quot;
  (interactive)
  (isearch-vim-style-exit)
  (call-interactively &apos;kill-ring-save)
  ;; set prefix arg to move point back to where search started
  (let ((current-prefix-arg &apos;(4)))
    (call-interactively &apos;set-mark-command)))&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dl id=&quot;footnotes&quot;&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;The code above has been modified from its original published state after &lt;a href=&quot;https://www.reddit.com/r/emacs/comments/f1x0jq/blog_post_my_first_emacs_lisp/&quot;&gt;feedback from Reddit&lt;/a&gt; and working with it some more. The original snippet looked like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-emacs-lisp&quot;&gt;(defun isearch-vim-style-exit ()
  &quot;Move point to the start of the matched string, regardless
    of search direction.&quot;
  (interactive)
  (when (eq isearch-forward t)
    (isearch-repeat &apos;backward))
  (isearch-exit))

(defun isearch-vim-style-kill ()
  &quot;Kill up to the search match when searching forward. When
    searching backward, kill to the beginning of the match.&quot;
  (interactive)
  (isearch-vim-style-exit)
  (call-interactively &apos;kill-region))

(defun isearch-vim-style-copy ()
  &quot;Copy up to the search match when searching forward. When
    searching backward, copy to the start of the search match.&quot;
  (interactive)
  (isearch-vim-style-exit)
  (call-interactively &apos;kill-ring-save)
  ;; set prefix arg to move point back to where search started
  (let ((current-prefix-arg &apos;(4)))
    (call-interactively &apos;set-mark-command)))&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/dd&gt;&lt;/dl&gt;</content:encoded></item><item><title><![CDATA[Tips and tricks for the fledgling Emacs user]]></title><description><![CDATA[In which I RTFM. It took about 18 months, but I finally decided to delve into the dark depths that is the Emacs manual, and I made it through alive. This document contains some of the things I learned along the way. Remember: I did this so you won't have to.]]></description><link>https://blog.thomasheartman.com/posts/tips-and-tricks-for-the-fledgling-emacs-user</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/tips-and-tricks-for-the-fledgling-emacs-user</guid><pubDate>Mon, 03 Feb 2020 07:31:30 GMT</pubDate><content:encoded>&lt;p&gt;Whenever I have gone looking for the Emacs equivalent of Drew Neil&apos;s amazing &lt;i&gt;Practical Vim/[fn:1], I have always found people recommending reading the Emacs manual, saying how good it is. For the longest time I put it off, and I was on the verge of ordering Mickey Petersen&apos;s /Mastering Emacs&lt;/i&gt;, which I also often see mentioned, when I decided that I should just bite the bullet and at least &lt;i&gt;start&lt;/i&gt; with the manual. It can&apos;t be that much of an undertaking, right? ... right?&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Wrong.&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Coming into 2020, I decided that I&apos;d get through the manual by the end of January. I had &lt;i&gt;no&lt;/i&gt; idea how much content was in there. Throughout the first 30 days of 2020 I sunk hour upon hour upon hour into this collection of text documents, assembled through many decades, until I finally found my way out, clothes tattered and torn, beard long and graying&lt;sup id=&quot;fnr-2&quot; class=&quot;footnote-ref&quot; data-label=&quot;2&quot;&gt;&lt;a href=&quot;#fn-2&quot;&gt;[2]&lt;/a&gt;&lt;/sup&gt;, but my mind opened and enlightened.&lt;/p&gt;&lt;p&gt;What I want to share today is not the entire voyage, but rather just the high points that come to mind when I think back on my journey. Undoubtedly there will be things I&apos;ve forgotten that should be here and things that are here that I should have forgotten, but such is the nature of human experiences. The best we can do is to just sit back and enjoy what we have.&lt;/p&gt;&lt;pre class=&quot;aside&quot;&gt;I will be using the same notation for key bindings as Emacs does in the manual. Most characters are just represented as themselves, but some are special. Chords (or modified keys) are represented as modifiers connected to letters by a hyphen. A list of the modifiers and special keys used in this document is presented below. More information on characters and notation can be found in [[https://www.gnu.org/software/emacs/manual/html_node/emacs/User-Input.html#User-Input][chapter 2]] of the Emacs manual.
  - ~C~ and ~M~ :: These upper case letters represent ~Control~ (your trusty control key) and ~Meta~ (usually alt), respectively. When used with other characters, they&apos;re connected by a hyphen: ~C-a~ and ~C-M-a~, for instance.
  - &amp;#x3C;RET&gt; :: The return (or enter) key
  - &amp;#x3C;ESC&gt; :: The escape key

In addition, note that ~M-x~ opens the ~execute-extended-command~ menu, wherein you can type in the name of a command. Thus, when you see something such as ~M-x other-window~, that means that the text after ~M-x~ is the name of the command. To execute the command, press return.&lt;/pre&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The Emacs key bindings&lt;/h2&gt;&lt;p&gt;Among the reasons to go through the manual, learning the &apos;proper&apos; Emacs key bindings was actually pretty high up. It might seem trivial, but there&apos;s been a number of times where I&apos;ve ended up in a state that I just can&apos;t navigate and don&apos;t know how to get out of.&lt;/p&gt;&lt;p&gt;As someone who fell in love with the Vim way of editing, I came to Emacs through &lt;a href=&quot;https://www.spacemacs.org/&quot;&gt;Spacemacs&lt;/a&gt;, which uses Evil mode to provide a very comfortable editing experience for Vim users. As such, I&apos;ve already spent a considerable amount of time learning one very specific set of key bindings (and I love it every day). Why would I bother learning another?&lt;/p&gt;&lt;p&gt;For some time, I&apos;ve been using &apos;hybrid-mode&apos;, giving me Vim key bindings in every mode except insert mode, where I switch to using Emacs key bindings. What I have discovered is that they both have their uses, and they shine in different ways. When navigating text, I feel much safer and much more agile in Vim&apos;s normal mode, able to take leaps and bounds through the buffer, working on text as objects, confident that I won&apos;t accidentally insert some text by a stray key press. However, when typing out text, having to exit insert mode and then type a command before entering insert mode again can be pretty tedious, and being able to make certain movements from that state just makes a lot of sense. A good example would be needing to go back to an earlier part of a line, delete some text, and then keep inserting at the end. In Vim, assuming we&apos;re already in insert-mode:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;&amp;#x3C;ESC&gt; ? &amp;#x3C;search term&gt; &amp;#x3C;RET&gt; d a w A&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And in Emacs&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;C-r &amp;#x3C;search term&gt; &amp;#x3C;RET&gt; M-d C-e&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If my counting is correct, the Vim version has three more key presses than the Emacs version. Unless you&apos;re into golfing, this probably doesn&apos;t mean much to you (especially if &lt;code&gt;d a w&lt;/code&gt; feels like a single movement to you), but to me, it &lt;i&gt;feels&lt;/i&gt; (subjective, I know) like more work.&lt;/p&gt;&lt;p&gt;A surprising key binding that I&apos;ve never really considered, but which Emacs has bound to &lt;code&gt;C-M-v&lt;/code&gt; by default: &lt;code&gt;scroll-other-window&lt;/code&gt;. If you have multiple windows open in a single frame, it&apos;ll scroll one of the other windows, but lets you keep your focus (and your cursor) in your current window. There may be a way to target a specific window, but I found it most useful when having only two windows open. If you have more than two windows open, it&apos;ll scroll the &lt;i&gt;next&lt;/i&gt; window as defined by Emacs buffer ordering. From what I can tell, this is left to right, top to bottom. It&apos;s the same order as when going through the windows by &lt;code&gt;C-x o&lt;/code&gt; (&lt;code&gt;other-window&lt;/code&gt;).&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Navigating text (&lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/emacs/Text.html#Text&quot;&gt;chapter 25&lt;/a&gt;)&lt;/h3&gt;&lt;p&gt;Naturally, coming from Vim, I think that the Vim way is &lt;i&gt;the&lt;/i&gt; way for navigating text on a screen. Or at least I did. In fact, I was surprised to learn that Emacs has all the same facilities for navigating a buffer as Vim does, and it turns out that all the same movement patterns that I rely on in Vim are available in Emacs; they&apos;re just bound to different keys.&lt;/p&gt;&lt;p&gt;There are a couple of editing patterns that I haven&apos;t found the equivalent of yet, though (send me tips if you&apos;ve got them!):&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;The equivalent of [[https://github.com/tpope/vim-surround][~vim-surround~]]&lt;/dt&gt;&lt;dd&gt;Yup, Evil has a function for it, and I&apos;m sure you can write a function that will contain text, change surrounding delimiters to something else, or delete surrounding delimiters, but it&apos;s not immediately available. That said, even in Vim, it&apos;s a plugin, so maybe this shouldn&apos;t count.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Delete to next search hit&lt;/dt&gt;&lt;dd&gt;In Vim (normal mode), a common way for me to operate on some text is to &lt;code&gt;d / &amp;#x3C;search string&gt; &amp;#x3C;RET&gt;&lt;/code&gt; to delete up until the first occurrence of the search string. I haven&apos;t found a way to do that in barebones Emacs. Emacs comes with the default binding of &lt;code&gt;M-z&lt;/code&gt; as &lt;code&gt;zap-to-char&lt;/code&gt;, which is almost what I want. However, rather than being able to input just a single character, I want to be able to input a search string and kill up to that point. It&apos;d be similar to &lt;code&gt;C-&amp;#x3C;SPC&gt; C-s &amp;#x3C;search string&gt; &amp;#x3C;RET&gt; &amp;#x3C;DEL&gt;&lt;/code&gt;, but without killing the actual search string (kill &lt;i&gt;up to&lt;/i&gt;, not &lt;i&gt;including&lt;/i&gt;), and it should be a single key chord. If I were to override the &lt;code&gt;M-z&lt;/code&gt; binding, it&apos;d be &lt;code&gt;M-z &amp;#x3C;search string&gt; &amp;#x3C;RET&gt;&lt;/code&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;Overall, though, I am surprisingly happy with Emacs&apos; movement keys, and while I don&apos;t think I&apos;ll be switching over completely just yet (or ever?), being able to navigate comfortably in either mode can only make things better.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The kill ring (&lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/emacs/Kill-Ring.html#Kill-Ring&quot;&gt;chapter 12.2.1&lt;/a&gt;)&lt;/h2&gt;&lt;p&gt;Of all the things I&apos;ve learned, this is probably the one that&apos;s given me the most bang for my buck. Whatever your preferred way of getting text into your kill ring (also known as the clipboard), once you&apos;ve got it there, Emacs doesn&apos;t just store the last entry, but rather your last 60 (by default) entries. The reason it&apos;s called a ring is that you can cycle through your entries, and once you reach the end, you loop back around.&lt;/p&gt;&lt;p&gt;So when you paste (or &lt;i&gt;yank&lt;/i&gt;) something into a buffer with &lt;code&gt;C-y&lt;/code&gt;, you can then follow that up by using &lt;code&gt;M-y&lt;/code&gt; to cycle through the kill ring. You can view the entire contents of the kill ring with &lt;code&gt;C-h v kill-ring&lt;/code&gt;, though be warned: the kill ring is displayed as lisp code, so it may not read as plainly as you&apos;d expect.&lt;/p&gt;&lt;p&gt;Side note: I wish Vim and Emacs could at least agree on the meaning of the word &apos;yank&apos;. Whether it means to &lt;i&gt;copy something from the buffer&lt;/i&gt; (Vim) or to &lt;i&gt;paste something into the buffer&lt;/i&gt; (Emacs), I don&apos;t care. Just pick one.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The undo-stack (&lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/emacs/Undo.html#Undo&quot;&gt;chapter 16.1&lt;/a&gt;)&lt;/h2&gt;&lt;p&gt;Spacemacs uses the undo-tree-mode (see &lt;a href=&quot;https://www.emacswiki.org/emacs/UndoTree&quot;&gt;the Emacs wiki entry&lt;/a&gt;) to store buffer states in a change tree. This is really intuitive and lets you visualize your changes in a graphical model that maps pretty well onto my view of a set of changes. What I wasn&apos;t aware of was that plain, ol&apos;, vanilla Emacs comes with a pretty uncommon, but super-powerful undo history out of the box: instead of taking the view that history branchces after undoing a change, the default undo is more like a strictly linear timeline. When you undo a change, Emacs simply pushes this onto the history &apos;stack&apos; as a new change. Thus, Emacs doesn&apos;t have a traditional &lt;i&gt;redo&lt;/i&gt; as such: it&apos;s just another undo.&lt;/p&gt;&lt;p&gt;It&apos;s a bit tricky to wrap your head around, but is really worth checking out. For context, here is an excerpt from the relevant chapter in the manual (&lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/emacs/Undo.html#Undo&quot;&gt;link to web version&lt;/a&gt;):&lt;/p&gt;&lt;blockquote&gt;To begin to undo, type ~‘C-/’~ (or its aliases, ~‘C-_’~ or ~‘C-x u’~). This undoes the most recent change in the buffer, and moves point back
to where it was before that change.  Consecutive repetitions of ~‘C-/’~ (or its aliases) undo earlier and earlier changes in the current buffer. If all the recorded changes have already been undone, the undo command signals an error.

Any command other than an undo command breaks the sequence of undo commands.  Starting from that moment, the entire sequence of undo commands that you have just performed are themselves placed into the undo record.  Therefore, to re-apply changes you have undone, type ~‘C-f’~ or any other command that harmlessly breaks the sequence of undoing; then type ~‘C-/’~ one or more times to undo some of the undo commands.

Alternatively, if you want to resume undoing, without redoing previous undo commands, use ~‘M-x undo-only’~.  This is like ‘undo’, but will not redo changes you have just undone.&lt;/blockquote&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Bookmarks (&lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/emacs/Bookmarks.html#Bookmarks&quot;&gt;chapter 13.8&lt;/a&gt;)&lt;/h2&gt;&lt;p&gt;When reading through a document in several sittings, it&apos;s useful to be able to jot down how far you&apos;d gotten so that you can easily resume your reading. To this end, Emacs has a bookmarks system which was very useful when reading through the documentation. Similarly to how one might use bookmarks in a web browser, I&apos;ve also bookmarked a number of documents to read later, so that I don&apos;t forget. In addition to being useful for reading, I can also imagine it being useful if you often need to refer back to a specific file when programming, though registers (&lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/emacs/Registers.html#Registers&quot;&gt;chapter 13&lt;/a&gt;), specifically File Registers (&lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/emacs/File-Registers.html#File-Registers&quot;&gt;chapter 13.6&lt;/a&gt;), may be better suited to this.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Amusements (&lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/emacs/Amusements.html#Amusements&quot;&gt;chapter 47&lt;/a&gt;)&lt;/h2&gt;&lt;p&gt;The Amusements chapter covers a couple of really neat, mostly useless, tricks that you can do with Emacs. It lists a couple of built-in games, including classics such as Snake, Pong, and Tetris (turns out I&apos;m horrible at that, by the way); text-based adventure games (&lt;code&gt;dunnet&lt;/code&gt;) and Conway&apos;s Game of Life simulation (&lt;code&gt;life&lt;/code&gt;); ways to convert a region into morse code or NATO phonetic alphabet (&lt;code&gt;morse-region&lt;/code&gt; and &lt;code&gt;nato-region&lt;/code&gt; to encode, &lt;code&gt;unmorse-region&lt;/code&gt; and &lt;code&gt;denato-region&lt;/code&gt; to decode); ways to play with the display when idling (&lt;code&gt;zone&lt;/code&gt;); and &lt;a href=&quot;https://xkcd.com/378&quot;&gt;references to XKCD&lt;/a&gt;.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Glasses mode (&lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/emacs/MixedCase-Words.html#MixedCase-Words&quot;&gt;chapter 26.9&lt;/a&gt;) and flipping tables&lt;/h3&gt;&lt;p&gt;In addition to being able to encode a region as morse or the NATO phonetic alphabet, Emacs also comes with something known as glasses mode. This isn&apos;t actually an amusement and is originally supposed to help make &lt;code&gt;camelCased&lt;/code&gt; words easier to read by turning them into &lt;code&gt;snake_cased&lt;/code&gt; words instead (or using any other separator that you want). This is all just presentational, so even though Emacs might display the identifier as &lt;code&gt;my_Favorite_Identifier&lt;/code&gt;, it&apos;ll get saved as &lt;code&gt;myFavoriteIdentifier&lt;/code&gt;, and when you edit the text, the underlines aren&apos;t actually there for you to edit.&lt;/p&gt;&lt;p&gt;Because you can change the separator, you can also use glasses mode to separate your identifiers with an arbitrary text string. My coworker suggested the &apos;table flip&apos;, and sure enough, Emacs is happy to comply:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;myFavoriteIdentifier&lt;/span&gt; = someOtherIdentifier&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;becomes&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;my&lt;/span&gt;(╯°□°）╯︵ ┻━┻&lt;span class=&quot;hljs-type&quot;&gt;Favorite&lt;/span&gt;(╯°□°）╯︵ ┻━┻&lt;span class=&quot;hljs-type&quot;&gt;Identifier&lt;/span&gt; = some(╯°□°）╯︵ ┻━┻&lt;span class=&quot;hljs-type&quot;&gt;Other&lt;/span&gt;(╯°□°）╯︵ ┻━┻&lt;span class=&quot;hljs-type&quot;&gt;Identifier&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;and for fun, here it is in morse&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;--/-.--/..-./.-/...-/---/.-./../-/./../-.././-./-/../..-./.././.-. -...- .../---/--/./---/-/...././.-./../-.././-./-/../..-./.././.-.&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Debugging (&lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/emacs/Debuggers.html#Debuggers&quot;&gt;chapter 27.6&lt;/a&gt;)&lt;/h2&gt;&lt;p&gt;This is something I want to get into at a later stage, and the manual makes it seem rather impressive. I&apos;ve not used a debugger at all since switching to Emacs, and while I usually manage just fine, I find myself longing for one every so often.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Compilation buffers and jumping to the next error (&lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/emacs/Compilation-Mode.html#Compilation-Mode&quot;&gt;chapter 27.2&lt;/a&gt;)&lt;/h2&gt;&lt;p&gt;Somewhat related to debugging is compiling your programs in your editor. While a lot of text editors have built-in terminals that you can run things in, I haven&apos;t often seen them also have the ability to jump to any errors that occurred during compilation, though I haven&apos;t actually gone looking. I am told, however, that this is fairly commonplace in applications known traditionally as IDEs. Emacs, eager not to disappoint, comes with support for this built in.&lt;/p&gt;&lt;p&gt;When using Emacs for compiling a program, it will usually open a &lt;i&gt;compilation buffer&lt;/i&gt;. If you have compilation errors, you can then use one of a number of keyboard shortcuts (my favorite is `M-g n`) to jump to the next compilation error. The best part is: this works from any buffer, even one not in compilation mode. In other words, if you have errors, you can jump through them sequentially without ever going back to the compilation buffer.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Indentation and programming indentation (&lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_mono/emacs.html#Indentation&quot;&gt;chapter 24&lt;/a&gt; and &lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_mono/emacs.html#Program-Indent&quot;&gt;chapter 26.3&lt;/a&gt;)&lt;/h2&gt;&lt;p&gt;There&apos;s a number of cool indentation tricks listed in the indentation and the program indentation chapters, but I think the one I found that the most useful was for indenting languages derived from C. For a detailed explanation, check out &lt;a href=&quot;https://www.gnu.org/software/emacs/manual/html_node/efaq/Customizing-C-and-C_002b_002b-indentation.html&quot;&gt;this page on customizing indentation in C, C++, and Java&lt;/a&gt;, but the short version of it is that you can analyze the various syntactic parts of your program directly in your buffer, and then tell Emacs how it should indent a specific construct.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Org mode&lt;/h2&gt;&lt;p&gt;What about org mode? You&apos;d think that that was one of the best parts of Emacs, and that I&apos;d have a ton of tips to share, right? Well, you&apos;re probably right, but org mode comes with its own manual (another pretty massive text document), and I haven&apos;t made my way through that one yet. Trust me, though: it&apos;s on my list of must-reads this year. I&apos;ll get to it later.&lt;/p&gt;&lt;hr&gt;&lt;p&gt;So that&apos;s the first item on my &lt;a href=&quot;https://blog.thomasheartman.com/posts/goodbye-2019-hello-2020&quot;&gt;SMART goal list&lt;/a&gt; completed. I&apos;m not quite ready to start configuring Emacs from scratch, but it doesn&apos;t feel that daunting anymore. Now: do I go to work on Kubernetes, or do I spend some extra time with org mode to get really comfy with Emacs?&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;/div&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;Seriously, if you&apos;re into Vim and haven&apos;t read it: I &lt;strong&gt;highly&lt;/strong&gt; recommend you take the time to go through it. For a beginner it&apos;s an absolute gem, and even for experienced vimmers, I&apos;m sure there&apos;s a good few tricks in there that you didn&apos;t know about.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[2]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-2&quot; class=&quot;footnote&quot; data-label=&quot;2&quot;&gt;&lt;p&gt;I &lt;i&gt;have&lt;/i&gt; actually found a grey hair in my beard this month (sshhh!) and I attribute that wholly to Emacs.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;dl id=&quot;footnotes&quot;&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[2]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-2&quot; class=&quot;footnote&quot; data-label=&quot;2&quot;&gt;&lt;p&gt;I &lt;i&gt;have&lt;/i&gt; actually found a grey hair in my beard this month (sshhh!) and I attribute that wholly to Emacs.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;&lt;/dl&gt;</content:encoded></item><item><title><![CDATA[Use git to restore parts of a file]]></title><description><![CDATA[In which we look at restoring parts of a file to its original state (or at least to what state it had at the specified commit). A handy workflow trick that uses the new git subcommand 'restore'.]]></description><link>https://blog.thomasheartman.com/posts/use-git-to-restore-parts-of-a-file</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/use-git-to-restore-parts-of-a-file</guid><pubDate>Mon, 27 Jan 2020 10:52:44 GMT</pubDate><content:encoded>&lt;p&gt;One of my favorite, little-known git tricks is using the &lt;code&gt;--patch&lt;/code&gt; option (&lt;code&gt;-p&lt;/code&gt; for short) to affect only parts of a file when you&apos;re adding, committing, or---as I recently found out---/restoring/.&lt;/p&gt;&lt;p&gt;Now some of you may be thinking &apos;hold up! Restoring a file? What&apos;s that?&apos; If you haven&apos;t been following git development for a while (while a solid project, it&apos;s not exactly the JS framework &lt;i&gt;du jour&lt;/i&gt;), you&apos;d be excused for not knowing about the two new git commands &lt;code&gt;switch&lt;/code&gt; and &lt;code&gt;restore&lt;/code&gt;. Introduced in git 2.23.0 (released in August 2019), these two commands were introduced to offload the &lt;code&gt;checkout&lt;/code&gt; command for switching branches and restoring files. As you may expect, &lt;code&gt;switch&lt;/code&gt; allows you to switch branches (and create new ones in the same way as &lt;code&gt;checkout -b&lt;/code&gt; by using &lt;code&gt;switch -c&lt;/code&gt;), and &lt;code&gt;restore&lt;/code&gt; takes over for restoring files from a previous commit.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;&lt;code&gt;git restore -p&lt;/code&gt;&lt;/h2&gt;&lt;p&gt;While there is lots to be said about the new commands and all the options they accept, I advise you to go check out the official docs for &lt;a href=&quot;https://git-scm.com/docs/git-switch&quot;&gt;~switch~&lt;/a&gt; and &lt;a href=&quot;https://git-scm.com/docs/git-restore&quot;&gt;~restore~&lt;/a&gt; for that. This post is about using &lt;code&gt;restore&lt;/code&gt; with the &lt;code&gt;-p&lt;/code&gt; option, specifically.&lt;/p&gt;&lt;p&gt;Sometimes (read: quite often) when making changes to a file, you have some changes that you want to keep and some that you want to discard. In situations like this, there&apos;s a number of ways to go about it. If the changes are ready to be staged or committed, you can use the &lt;code&gt;-p&lt;/code&gt; option to pick the parts you want and then just restore the file afterwards. However, in the event that the changes you want aren&apos;t quite ready just yet, and you don&apos;t want to stage, restore, and unstage, you might want to consider using &lt;code&gt;restore -p&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;By default, &lt;code&gt;restore -p&lt;/code&gt; brings up an interactive prompt that lists the differences between your working tree and the last commit, asking you in turn whether you want to discard each hunk. This way, if you have some changes in one part of the file that you don&apos;t want to keep, you can discard those, but keep the rest. As per usual with the &lt;code&gt;--patch&lt;/code&gt; option, you can also split hunks or edit them manually if you need to.&lt;/p&gt;&lt;p&gt;When not given any paths to act on, &lt;code&gt;git restore -p&lt;/code&gt; will ask you about all your unstaged changes in all your files. To limit it to a specific file, supply a pathspec: &lt;code&gt;git restore -p myfile.txt&lt;/code&gt;. The documentation says that &apos;&lt;code&gt;--patch&lt;/code&gt; can accept no pathspec and will prompt to restore all modified paths.&apos;&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;, but when testing it out using git version 2.23.1, using pathspecs was no problem at all.&lt;/p&gt;&lt;p&gt;In addition to the default patch restoration functionality, some of the other notable options are:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;~-s &amp;#x3C;tree&gt;~ / ~--source=&amp;#x3C;tree&gt;~&lt;/dt&gt;&lt;dd&gt;Use this option if you want to restore a file to a different commit than HEAD. What you pick as your &lt;code&gt;source&lt;/code&gt; can be another branch, a commit hash, or something like &lt;code&gt;HEAD~2&lt;/code&gt;. Without the &lt;code&gt;--patch&lt;/code&gt; flag, this will change the entire file to reflect the state at that &lt;code&gt;source&lt;/code&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;~-S~ / ~--staged~&lt;/dt&gt;&lt;dd&gt;Not to be confused with the lowercase &lt;code&gt;-s&lt;/code&gt; above, the &lt;code&gt;-S&lt;/code&gt; option allows you to restore changes from the index (your staging area or &apos;added files&apos;). By default, &lt;code&gt;restore&lt;/code&gt; only works on files in your work tree. Using this option will make it work only on files in your staging area. To act on both at once, supply both the &lt;code&gt;-S&lt;/code&gt; and the &lt;code&gt;-W&lt;/code&gt; (&lt;code&gt;--worktree&lt;/code&gt;)  options: &lt;code&gt;git restore -SW&lt;/code&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;p&gt;&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;https://git-scm.com/docs/git-restore#Documentation/git-restore.txt---patch&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[feature(slice_patterns)]]></title><description><![CDATA[In which we look at the upcoming stable Rust feature 'slice_patterns' (due to stabilize in 1.42.0). We look at the syntax, subslice binding, and how you can match on either end of a slice.]]></description><link>https://blog.thomasheartman.com/posts/feature(slice_patterns)</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/feature(slice_patterns)</guid><pubDate>Mon, 20 Jan 2020 07:56:09 GMT</pubDate><content:encoded>&lt;p&gt;About a week ago, there was an item in &lt;a href=&quot;https://this-week-in-rust.org/&quot;&gt;This Week in Rust&lt;/a&gt; (&lt;a href=&quot;https://this-week-in-rust.org/blog/2020/01/07/this-week-in-rust-320/&quot;&gt;issue 320&lt;/a&gt;) that caught my eye under the &lt;i&gt;Tracking Issues &amp;#x26; PRs&lt;/i&gt; heading:&lt;/p&gt;&lt;blockquote&gt;[disposition: merge] Stabilize ~#![feature(slice_patterns)]~ in 1.42.0.&lt;/blockquote&gt;&lt;p&gt;Aww, yeah! I&apos;ve been waiting for this for literal years, so you better believe that was a good day! I mentioned this in my &lt;a href=&quot;https://blog.thomasheartman.com/posts/rust-2020/&quot;&gt;Rust 2020 post&lt;/a&gt; as one of the things I&apos;m the most excited to see this year, so now that it&apos;s getting stabilized soon (2020-03-12), let&apos;s make sure we&apos;re prepared!&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;About slice patterns&lt;/h2&gt;&lt;pre class=&quot;aside&quot;&gt;Most of the information contained in this section can also be found in the [[https://github.com/rust-lang/rust/pull/67712][RFC]] on GitHub. The RFC is very thorough and gives lots of examples, so go give it a read if you want to know more about the feature!&lt;/pre&gt;&lt;p&gt;We&apos;ve had some form of slice matching on stable Rust for a while now, but without this feature, the form of matching you can do is rather limited. With an array of a known length, you can destructure and match as you please, but for slices of an unknown length, you must provide a fallback because there is no way to cover all the potential cases in a &lt;code&gt;match&lt;/code&gt; expression. Also, quite importantly: there is no way to bind variables to subslices. This feature finally opens the gates to subslice and subarray matching, mitigating both the above issues, and making slice patterns immensely more powerful.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Two flavors&lt;/h3&gt;&lt;p&gt;There are two syntactic flavors for the new subslice patterns: one for when you want to bind a subslice to a variable, and one for when you just want to denote that there are elided elements. Both flavors use the &lt;code&gt;..&lt;/code&gt; pattern (referred to as a &lt;i&gt;rest pattern&lt;/i&gt;) to match a variable number of elements. The number of elements matched depend on the length of the array or slice and the number of matching elements before and after in the match.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h4&gt;Matching without binding&lt;/h4&gt;&lt;p&gt;Looking at the first flavor, &lt;strong&gt;matching without binding&lt;/strong&gt;, we get introduced to the &lt;code&gt;..&lt;/code&gt; pattern straight away:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T&gt;(xs: &amp;#x26;[T])
&lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;
    T: std::fmt::&lt;span class=&quot;hljs-built_in&quot;&gt;Debug&lt;/span&gt;,
{
    &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; xs {
        &lt;span class=&quot;hljs-comment&quot;&gt;// the slice has at least two variables.&lt;/span&gt;
        &lt;span class=&quot;hljs-comment&quot;&gt;// we bind the first and last items of&lt;/span&gt;
        &lt;span class=&quot;hljs-comment&quot;&gt;// the slice to `x` and `y`, respectively&lt;/span&gt;
        [x, .., y] =&gt; {
            &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;First and last: {:?} and {:?}.&quot;&lt;/span&gt;, x, y)
        }

        &lt;span class=&quot;hljs-comment&quot;&gt;// the slice has a single item: `x`&lt;/span&gt;
        [x] =&gt; {
          &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;the slice has a single item: {:?}.&quot;&lt;/span&gt;, x)
        }

        &lt;span class=&quot;hljs-comment&quot;&gt;// the slice is empty&lt;/span&gt;
        [] =&gt; {
            &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;Got an empty slice.&quot;&lt;/span&gt;)
        }
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Remember that &lt;code&gt;..&lt;/code&gt; can match any number of elements, &lt;strong&gt;including 0&lt;/strong&gt;. This means that the first pattern matches anything that has at least two items. You can also use the pattern without &apos;delimiting&apos; it on both ends, such as if you wanted to implement these two functions for getting the first and last element of a slice:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;first&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T&gt;(xs: &amp;#x26;[T]) -&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;Option&lt;/span&gt;&amp;#x3C;&amp;#x26;T&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; xs {
        [x, ..] =&gt; &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(x),
        [] =&gt; &lt;span class=&quot;hljs-literal&quot;&gt;None&lt;/span&gt;,
    }
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;last&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T&gt;(xs: &amp;#x26;[T]) -&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;Option&lt;/span&gt;&amp;#x3C;&amp;#x26;T&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; xs {
        [.., x] =&gt; &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(x),
        [] =&gt; &lt;span class=&quot;hljs-literal&quot;&gt;None&lt;/span&gt;,
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Notice how both of these functions pick out a single element of the slice (first and last respectively) and ignore the rest. Because &lt;code&gt;..&lt;/code&gt; matches 0 or more elements, the first pattern in both functions matches slices with &lt;strong&gt;one or more&lt;/strong&gt; elements.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h4&gt;Matching and binding a subslice&lt;/h4&gt;&lt;p&gt;The other flavor lets you &lt;strong&gt;bind a subslice to a value&lt;/strong&gt;, which takes slice patterns and cranks the power level up another notch or two. The binding is done using the &lt;code&gt;@&lt;/code&gt; operator.&lt;/p&gt;&lt;p&gt;Imagine for instance that we want to write a &lt;code&gt;sum&lt;/code&gt; function. That could be done as such:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;sum&lt;/span&gt;&lt;/span&gt;(xs: &amp;#x26;[&lt;span class=&quot;hljs-built_in&quot;&gt;i32&lt;/span&gt;]) -&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;i32&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; xs {
        [] =&gt; &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;,
        [x, xs @ ..] =&gt; x + sum(xs),
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In the example above, if the slice is not empty, we take the first element, &lt;code&gt;x&lt;/code&gt;, and add it to the result of summing the rest of the list, &lt;code&gt;xs&lt;/code&gt;. With Rust already having a &lt;code&gt;sum&lt;/code&gt; method on iterators, this function is pretty redundant, but it makes a good example of how to bind and use subslices.&lt;/p&gt;&lt;p&gt;Another example would be to get the middle element of a slice if the slice has an odd number of elements. If the slice is empty or has an even number of elements, return &lt;code&gt;None&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;middle&lt;/span&gt;&lt;/span&gt;&amp;#x3C;T&gt;(xs: &amp;#x26;[T]) -&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;Option&lt;/span&gt;&amp;#x3C;&amp;#x26;T&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; xs {
        &lt;span class=&quot;hljs-comment&quot;&gt;// ignore the first and last element.&lt;/span&gt;
        &lt;span class=&quot;hljs-comment&quot;&gt;// recurse with what&apos;s in between.&lt;/span&gt;
        [_, inner @ .., _] =&gt; middle(inner),

        &lt;span class=&quot;hljs-comment&quot;&gt;// one element! got it!&lt;/span&gt;
        [x] =&gt; &lt;span class=&quot;hljs-literal&quot;&gt;Some&lt;/span&gt;(x),

        &lt;span class=&quot;hljs-comment&quot;&gt;// oops! there&apos;s nothing here.&lt;/span&gt;
        [] =&gt; &lt;span class=&quot;hljs-literal&quot;&gt;None&lt;/span&gt;,
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Here we iterate through the slice from both sides, continuously picking off one element at the start and one element at the end. Whatever is left in the middle (if there are at least two elements) gets assigned to &lt;code&gt;xs&lt;/code&gt; and used as input to another step through the function. Once we have either one or zero elements left, we have our answer.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Why this is a big deal&lt;/h2&gt;&lt;p&gt;It might come across as somewhat strange that I&apos;m so enthused about a feature that may seem rather small, but it&apos;s one of those quality of life things that I find myself running into all the time. Being used to Haskell and their pattern matching behavior, I always forget how cumbersome it is to match on an arbitrary slice in Rust. Up until now, we&apos;ve had the &lt;a href=&quot;https://doc.rust-lang.org/std/primitive.slice.html#method.split_first&quot;&gt;~split_first~&lt;/a&gt; method (and &lt;code&gt;split_at&lt;/code&gt;) on slices, which I can never remember the name of, which returns an &lt;code&gt;Option&lt;/code&gt;, and which doesn&apos;t let you do arbitrary match-stuff (such as using match guards, for instance). The new &lt;code&gt;slice_patterns&lt;/code&gt; feature is a major step up in that regard.&lt;/p&gt;&lt;p&gt;The other thing that I&apos;m super jazzed about? Being able to match on the end of a slice. Not only can you pick off items from either end of the slice, but you can also make sure that the slice ends in a certain value or series of values.&lt;/p&gt;&lt;hr&gt;&lt;p&gt;In short, I think this is an &lt;i&gt;amazing&lt;/i&gt; addition to stable Rust. Hats off to all the people that have made it possible. Now go read &lt;a href=&quot;https://github.com/rust-lang/rust/pull/67712&quot;&gt;the RFC&lt;/a&gt; and look out for all the other cool stuff they&apos;re talking about (arbitrarily nested OR patterns? Oh, my!).&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Let's read: Haskell Programming from First Principles, pt X]]></title><description><![CDATA[In which we go deep on folding lists and uncover surprisingly large and important differences between folding right and folding left. We discuss laziness, infinite lists, and catamorphisms.]]></description><link>https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-x</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-x</guid><pubDate>Mon, 13 Jan 2020 10:23:48 GMT</pubDate><content:encoded>&lt;p&gt;A whole chapter dedicated to folding lists? I thought it would be quick and easy, but it turns out there&apos;s a lot of things to uncover in regards to folding. In this post we&apos;ll be looking at what a fold is and how folding left differs from folding right.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;A brief explanation of folding&lt;/h2&gt;&lt;p&gt;Before we can talk about folding left or right, it&apos;s important to know what we&apos;re talking about. In short, a fold is a way to reduce a data structure (lists in our case) to some other type by working through the data structure. If that sounds unclear, a more concrete example could be a function that sums all the numbers in a list or a function which tells you whether any element of a list satisfies a predicate.&lt;/p&gt;&lt;p&gt;Let&apos;s look at &lt;code&gt;foldr&lt;/code&gt;, short for &apos;fold right&apos;. We&apos;ll talk about &lt;code&gt;foldl&lt;/code&gt; (fold left) in a bit. The signature for &lt;code&gt;foldr&lt;/code&gt; is as follows as taken from GHCi, version 8.6.5:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Foldable&lt;/span&gt; (&lt;span class=&quot;hljs-title&quot;&gt;t&lt;/span&gt; :: * -&gt; *) &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;&lt;/span&gt;
  foldr :: (a -&gt; b -&gt; b) -&gt; b -&gt; t a -&gt; b&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We haven&apos;t talked about &lt;i&gt;kinds&lt;/i&gt; yet (that&apos;s in the next chapter), but the &lt;code&gt;t :: * -&gt; *&lt;/code&gt; part means that &lt;code&gt;t&lt;/code&gt; is a type that is parameterized by another type. In our instance, we can substitute it with a list instead:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;foldr&lt;/span&gt; :: (a -&gt; b -&gt; b) -&gt; b -&gt; [a] -&gt; b&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So &lt;code&gt;foldr&lt;/code&gt; is a higher-order function that relies on two parametrically polymorphic types, &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt;. It takes a function from &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; to &lt;code&gt;b&lt;/code&gt;, an initial &lt;code&gt;b&lt;/code&gt; value, a list (or &lt;code&gt;Foldable&lt;/code&gt;) of &lt;code&gt;a&lt;/code&gt;, and returns a &lt;code&gt;b&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;This snippet is taken from the &lt;a href=&quot;https://wiki.haskell.org/Fold&quot;&gt;Haskell Wiki article on folding&lt;/a&gt; (which I recommend you take a look at if you&apos;re not quite familiar with it), and shows the equations defining &lt;code&gt;foldr&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;-- if the list is empty, the result is the initial value z; else&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;-- apply f to the first element and the result of folding the rest&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;foldr&lt;/span&gt; f z []     = z
&lt;span class=&quot;hljs-title&quot;&gt;foldr&lt;/span&gt; f z (x:xs) = f x (foldr f z xs)&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In the above snippet &lt;code&gt;f&lt;/code&gt; is the &lt;code&gt;(a -&gt; b -&gt; b)&lt;/code&gt;, &lt;code&gt;z&lt;/code&gt; is the &lt;code&gt;b&lt;/code&gt;, and the &lt;code&gt;[a]&lt;/code&gt; is either destructured into &lt;code&gt;[]&lt;/code&gt; or &lt;code&gt;(x:xs)&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;Folds are &lt;i&gt;catamorphisms&lt;/i&gt;, a way of deconstructing data, reducing a structure to a completely different result.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Why direction matters: &lt;code&gt;foldr&lt;/code&gt; vs &lt;code&gt;foldl&lt;/code&gt;&lt;/h2&gt;&lt;p&gt;Building on the basic definition of a fold, let&apos;s explore the differences between folding left and folding right and what impacts that has on your programs.&lt;/p&gt;&lt;p&gt;Let&apos;s revisit the definition of &lt;code&gt;foldr&lt;/code&gt;, but this time put &lt;code&gt;foldl&lt;/code&gt; just below it. Again, the snippet is taken from the &lt;a href=&quot;https://wiki.haskell.org/Fold&quot;&gt;Haskell Wiki article on folding&lt;/a&gt;, but I&apos;ve added the function types for clarity.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;-- if the list is empty, the result is the initial value z; else&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;-- apply f to the first element and the result of folding the rest&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;foldr&lt;/span&gt; :: (a -&gt; b -&gt; b) -&gt; b -&gt; [a] -&gt; b
&lt;span class=&quot;hljs-title&quot;&gt;foldr&lt;/span&gt; f z []     = z
&lt;span class=&quot;hljs-title&quot;&gt;foldr&lt;/span&gt; f z (x:xs) = f x (foldr f z xs)

&lt;span class=&quot;hljs-comment&quot;&gt;-- if the list is empty, the result is the initial value; else&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;-- we recurse immediately, making the new initial value the result&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;-- of combining the old initial value with the first element.&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;foldl&lt;/span&gt; :: (b -&gt; a -&gt; b) -&gt; b -&gt; [a] -&gt; b
&lt;span class=&quot;hljs-title&quot;&gt;foldl&lt;/span&gt; f z []     = z
&lt;span class=&quot;hljs-title&quot;&gt;foldl&lt;/span&gt; f z (x:xs) = foldl f (f z x) xs&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;These two functions are nearly identical, but they flip the order of the parameters of the first function and they behave quite differently. Notice how &lt;code&gt;foldr&lt;/code&gt; applies &lt;code&gt;f&lt;/code&gt; to &lt;code&gt;x&lt;/code&gt; and then to the result of folding the rest of the list, while &lt;code&gt;foldl&lt;/code&gt; immediately recurses before applying &lt;code&gt;f&lt;/code&gt; to &lt;code&gt;z&lt;/code&gt; and &lt;code&gt;x&lt;/code&gt;. This may seem unimportant, but it has big ramifications in a lazy language like Haskell.&lt;/p&gt;&lt;p&gt;With &lt;code&gt;foldr&lt;/code&gt;, if you have a function that lazily evaluates its arguments, you could potentially short-circuit the recursion long before reaching the end of the list, but with &lt;code&gt;foldl&lt;/code&gt;, because the function recurses immediately, you force the evaluation of the entire list. This means that if you have an infinite list, &lt;code&gt;foldl&lt;/code&gt; will never finish, while &lt;code&gt;foldr&lt;/code&gt; might.&lt;/p&gt;&lt;p&gt;Let&apos;s see an example. If we want to use &lt;code&gt;foldr&lt;/code&gt; to find whether any number in an infinite list is even, we could do it like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;foldr&lt;/span&gt; (\x b -&gt; even x || b) &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt; [ &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt; .. ]
&lt;span class=&quot;hljs-comment&quot;&gt;-- returns True&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Even if the list is infinite, the function we pass to &lt;code&gt;foldr&lt;/code&gt; doesn&apos;t evaluate its second parameter (&lt;code&gt;b&lt;/code&gt;) if &lt;code&gt;even x&lt;/code&gt; evaluates to &lt;code&gt;True&lt;/code&gt;. In the example above, the evaluation would work a little something like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;-- the list is not empty, so apply f to the head of the list&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;-- and set up potential recursion&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;even&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt; || foldr (\x b -&gt; even x || b) &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt; [ &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; .. ]
&lt;span class=&quot;hljs-comment&quot;&gt;-- even 1 is False, so we take another step and recurse.&lt;/span&gt;

&lt;span class=&quot;hljs-title&quot;&gt;even&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; || foldr (\x b -&gt; even x || b) &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt; [ &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt; .. ]
&lt;span class=&quot;hljs-comment&quot;&gt;-- even 2 is True, so we don&apos;t need to evaluate anymore.&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;-- we can happily return the result with only two steps.&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In this example, the function can exit after only two steps through the list because our function (&lt;code&gt;\x b -&gt; even x || b&lt;/code&gt;) doesn&apos;t evaluate &lt;code&gt;b&lt;/code&gt; unless &lt;code&gt;even x&lt;/code&gt; is False. If we look at the same example with &lt;code&gt;foldl&lt;/code&gt;, however, the result is quite different:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;-- note the flipped parameter order for f&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;foldl&lt;/span&gt; (\b x -&gt; even x || b) &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt; [ &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt; .. ]
&lt;span class=&quot;hljs-comment&quot;&gt;-- ... ... ... ...&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;-- never terminates&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Because &lt;code&gt;foldl&lt;/code&gt; recurses unconditionally (&lt;code&gt;foldl f (f z x) xs&lt;/code&gt;), the function will start to evaluate, but because it needs to get to the end of the list before it can evaluate the function and because the list is infinite, the function can never terminate.&lt;/p&gt;&lt;p&gt;&lt;code&gt;foldr&lt;/code&gt;, on the other hand, doesn&apos;t recurse immediately, and flips back and forth between evaluating &lt;code&gt;f&lt;/code&gt; and taking another step. This means that, because of lazy evaluation, &lt;code&gt;foldr&lt;/code&gt; can stop recursing through the list after any number iterations, depending on the function.&lt;/p&gt;&lt;p&gt;Let&apos;s relate back to what we talked about &lt;a href=&quot;https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-ix/&quot;&gt;last time&lt;/a&gt; and talk about &lt;i&gt;spines&lt;/i&gt;. Folding happens in two stages: traversal and folding. Traversal is the stage in which the fold recurses over the spine. Folding is the evaluation of the folding function applied to the values. All folds recurse over the spine in the same direction. However, the difference lies in the association of the folding function and direction the folding proceeds. This sounds tricky, but we can demonstrate it by parenthesizing:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;foldr&lt;/span&gt; (+) &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; [ &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt; .. &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; ]
&lt;span class=&quot;hljs-comment&quot;&gt;-- evaluates as the following&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;-- (1+(2+(3+(4+(5+0)))))&lt;/span&gt;

&lt;span class=&quot;hljs-title&quot;&gt;foldl&lt;/span&gt; (+) &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; [ &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt; .. &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; ]
&lt;span class=&quot;hljs-comment&quot;&gt;-- evaluates as the following&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;-- (((((0+1)+2)+3)+4)+5)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Notice how the order in which the expressions are evaluated is reversed, as is the end at which the zero element is applied. If we use a non-commutative operation instead of summing, we&apos;ll see the last point more clearly:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;foldr&lt;/span&gt; (++) &lt;span class=&quot;hljs-string&quot;&gt;&quot;0&quot;&lt;/span&gt; [&lt;span class=&quot;hljs-string&quot;&gt;&quot;a&quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&quot;b&quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&quot;c&quot;&lt;/span&gt;]
&lt;span class=&quot;hljs-comment&quot;&gt;-- evaluates to &quot;abc0&quot;&lt;/span&gt;

&lt;span class=&quot;hljs-title&quot;&gt;foldl&lt;/span&gt; (++) &lt;span class=&quot;hljs-string&quot;&gt;&quot;0&quot;&lt;/span&gt; [&lt;span class=&quot;hljs-string&quot;&gt;&quot;a&quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&quot;b&quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&quot;c&quot;&lt;/span&gt;]
&lt;span class=&quot;hljs-comment&quot;&gt;-- evaluates to &quot;0abc&quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Notice how the &lt;code&gt;0&lt;/code&gt; ends up at opposite ends of the result because of the evaluation order.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Folding summary&lt;/h3&gt;&lt;p&gt;In short, the book recommends to always use &lt;code&gt;foldr&lt;/code&gt; over &lt;code&gt;foldl&lt;/code&gt; and provides a helpful summary:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;code&gt;foldr&lt;/code&gt; ::&lt;/li&gt;&lt;ol&gt;&lt;li&gt;The recursive invocation of &lt;code&gt;foldr&lt;/code&gt; is an argument to the folding function. It doesn&apos;t directly self-call as a tail call the way &lt;code&gt;foldl&lt;/code&gt; does. In a way, you can think of &lt;code&gt;foldr&lt;/code&gt; as alternating between applications of the folding function &lt;code&gt;f&lt;/code&gt; and &lt;code&gt;foldr&lt;/code&gt;, where the next invocation of &lt;code&gt;foldr&lt;/code&gt; is dependent on &lt;code&gt;f&lt;/code&gt; asking for it.&lt;/li&gt;&lt;li&gt;Is right-associative.&lt;/li&gt;&lt;li&gt;Works with infinite lists.&lt;/li&gt;&lt;li&gt;Is a good default choice for transforming data structures.&lt;/li&gt;&lt;/ol&gt;&lt;li&gt;&lt;code&gt;foldl&lt;/code&gt; ::&lt;/li&gt;&lt;ol&gt;&lt;li&gt;Self-calls (tail call) through the list, starts to produce values after reaching the very end.&lt;/li&gt;&lt;li&gt;Is left-associative.&lt;/li&gt;&lt;li&gt;Cannot be used with infinite lists.&lt;/li&gt;&lt;li&gt;Is &apos;nearly useless&apos; and should almost always be replaced with &lt;code&gt;foldl&apos;~. We haven&apos;t talked about ~foldl&apos;~, but it works the same as ~foldl&lt;/code&gt; except it is strict, meaning it evaluates the values inside the cons-cells as it traverses the list, rather than leaving them as unevaluated expressions. We&apos;ll talk more about this when we get to the chapter on efficient code.&lt;/li&gt;&lt;/ol&gt;&lt;/ul&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Definitions&lt;/h2&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Fold&lt;/dt&gt;&lt;dd&gt;A higher-order function that takes an accumulating function and a recursive data structure and returns the value that results from applying the function to the elements in the structure.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Catamorphism&lt;/dt&gt;&lt;dd&gt;A generalization of folds to arbitrary data types. A &lt;i&gt;morphism&lt;/i&gt; is a transformation, and &lt;i&gt;cata&lt;/i&gt; means &apos;down&apos; or &apos;against&apos;, so a &lt;i&gt;catamorphism&lt;/i&gt; is a transformation to a &apos;lower&apos; form.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Tail call&lt;/dt&gt;&lt;dd&gt;A &lt;i&gt;tail call&lt;/i&gt; is the final result of a function, i.e. the last function that gets called in a function. In the below example---assuming &lt;code&gt;g&lt;/code&gt; and &lt;code&gt;h&lt;/code&gt; are functions---~h~ is the tail call.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt; x y = h (g x y)&lt;/code&gt;&lt;/pre&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Tail recursion&lt;/dt&gt;&lt;dd&gt;a function whose tail calls are recursive invocations of itself. In our definitions of &lt;code&gt;foldr&lt;/code&gt; and &lt;code&gt;foldl&lt;/code&gt;, we see that &lt;code&gt;foldl&lt;/code&gt; is tail recursive, while &lt;code&gt;foldr&lt;/code&gt; is not, as the latter &lt;i&gt;alternates&lt;/i&gt; between calling &lt;code&gt;f&lt;/code&gt; and &lt;code&gt;foldr&lt;/code&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Summary&lt;/h2&gt;&lt;p&gt;In addition to going deep on folding, this chapter also touches briefly on the scan functions &lt;code&gt;scanl&lt;/code&gt; and &lt;code&gt;scanr&lt;/code&gt;. In the interest of time I won&apos;t cover them here (unless we need them later), but if you&apos;re interested you can go check out &lt;a href=&quot;https://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html#v:scanr&quot;&gt;Hackage&lt;/a&gt; for more information.&lt;/p&gt;&lt;p&gt;Next chapter is on Algebraic Data Types, and it&apos;s a big one, so stay tuned.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Let's read: Haskell Programming from First Principles, pt IX]]></title><description><![CDATA[In which we take a deep dive into the world of lists by looking at list creation, list comprehension, and about spines and non-strict evaluation. As it turns out, this has some pretty interesting implications.]]></description><link>https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-ix</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-ix</guid><pubDate>Mon, 06 Jan 2020 22:55:25 GMT</pubDate><content:encoded>&lt;p&gt;Ah, another data type deep dive! This time we&apos;re looking at lists and how they are created and evaluated. Not much more of an introduction needed here; let&apos;s just dive right in!&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;List creation&lt;/h2&gt;&lt;p&gt;There&apos;s a number of ways to construct lists in Haskell. This chapter covers using ranges and list comprehensions, both of which are quite neat and something I get deep personal satisfaction out of (&lt;i&gt;hey, I&apos;m not weird!&lt;/i&gt;).&lt;/p&gt;&lt;p&gt;We covered &lt;strong&gt;ranges&lt;/strong&gt; when looking at the &lt;code&gt;Enum&lt;/code&gt; typeclass in &lt;a href=&quot;https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-vi/&quot;&gt;Chapter 6&lt;/a&gt;, so let&apos;s just do a quick refresher: In Haskell you can create lists out of anything that implements the &lt;code&gt;Enum&lt;/code&gt; typeclass (such as &lt;code&gt;Int&lt;/code&gt; and &lt;code&gt;Char&lt;/code&gt; and &lt;code&gt;Bool&lt;/code&gt;) by using the syntactic range sugar:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;-- expression and what they evaluate to&lt;/span&gt;
[ &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt; .. &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; ] &lt;span class=&quot;hljs-comment&quot;&gt;-- [1, 2, 3, 4, 5]&lt;/span&gt;
[ &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt; .. ] &lt;span class=&quot;hljs-comment&quot;&gt;-- an infinite list of integers, each entry increasing by 1&lt;/span&gt;
[ &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt; .. ] &lt;span class=&quot;hljs-comment&quot;&gt;-- an infinite list of integers, each entry increasing by 2&lt;/span&gt;
[ &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; .. &lt;span class=&quot;hljs-number&quot;&gt;10&lt;/span&gt; ] &lt;span class=&quot;hljs-comment&quot;&gt;-- [1, 5, 9] (step size is 5-1 = 4)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Neat, huh? Just keep in mind that the range must be in increasing order. If you try something like &lt;code&gt;[5 .. 1]&lt;/code&gt;, you&apos;ll get an empty list.&lt;/p&gt;&lt;p&gt;In addition to ranges, there&apos;s also this thing called &lt;strong&gt;list comprehension&lt;/strong&gt;. List comprehensions are something I normally associate with Python, but I think Haskell&apos;s version is &lt;i&gt;much&lt;/i&gt; cooler. The syntax looks a lot like set comprehension does in mathematics (which is also where the concept comes from). A list comprehension requires at least one list (called a &lt;i&gt;generator&lt;/i&gt;) that provides an input for the comprehension. Here&apos;s a simple comprehension:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;[ x^&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; | x &amp;#x3C;- [&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt; .. &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;] ] &lt;span class=&quot;hljs-comment&quot;&gt;-- [1, 4, 9, 16, 25]&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The first bit before the pipe, &lt;code&gt;x^2&lt;/code&gt;, is the expression that goes into every cell. The variable &lt;code&gt;x&lt;/code&gt; is assigned from the generator &lt;code&gt;[1 .. 5]&lt;/code&gt;. Indeed, what this list comprehension does is simply to square each number of the generator. The same result could be achieved by a simple map: &lt;code&gt;map (^2) [1 .. 5]&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;Where list comprehensions really shine, however, is when you start to add more variables and optional filters. When adding more variables, the comprehension will create a list with every possible permutation of those values. For instance: say you want to create a list of all the positions in a 3x3 grid around an origin (&lt;code&gt;(-1, -1)&lt;/code&gt; to &lt;code&gt;(1, 1)&lt;/code&gt;). Using list comprehensions, that&apos;s trivial:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;[ (x, y) | x &amp;#x3C;- [&lt;span class=&quot;hljs-number&quot;&gt;-1&lt;/span&gt; .. &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;], y &amp;#x3C;- [&lt;span class=&quot;hljs-number&quot;&gt;-1&lt;/span&gt; .. &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;] ]&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In addition to variables, you can also add filters after the variables. Say you want the same list as above, but you don&apos;t want to include the origin (&lt;code&gt;(0, 0)&lt;/code&gt;):&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;[ (x, y) | x &amp;#x3C;- [&lt;span class=&quot;hljs-number&quot;&gt;-1&lt;/span&gt; .. &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;], y &amp;#x3C;- [&lt;span class=&quot;hljs-number&quot;&gt;-1&lt;/span&gt; .. &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;], (x, y) /= (&lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;) ]&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And not just &lt;i&gt;one&lt;/i&gt; filter; you can add multiple! What if we want a bigger list, but only want the tiles where the &lt;a href=&quot;https://www.wikiwand.com/en/Taxicab_geometry&quot;&gt;Manhattan distance&lt;/a&gt; to the origin is divisible by 7 (and excluding the origin itself)?&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;[ (x, y) | x &amp;#x3C;- [&lt;span class=&quot;hljs-number&quot;&gt;-4&lt;/span&gt; .. &lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;], y &amp;#x3C;- [&lt;span class=&quot;hljs-number&quot;&gt;-4&lt;/span&gt; .. &lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;], (x, y) /= (&lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;), (abs x + abs y) `mod` &lt;span class=&quot;hljs-number&quot;&gt;7&lt;/span&gt; == &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; ]&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;It may be a farfetched example, but I think it adequately shows just how cool list comprehensions can be in Haskell.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Spines and non-strict evaluation&lt;/h2&gt;&lt;p&gt;To talk about list evaluation, we need to talk about how lists are represented. To talk about how lists are represented, we need to talk about spines. But let&apos;s take a step back. It&apos;s not all that scary.&lt;/p&gt;&lt;p&gt;The list data type is defined as such:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;data&lt;/span&gt; [] a = [] | a : [a]&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;It&apos;s a recursive data structure. It&apos;s either an empty list, or an element prepended to another list. Syntactically, when we write lists or print them, they&apos;re usually presented like this: &lt;code&gt;[1, 2, 3]&lt;/code&gt;, but can also be thought of as &lt;code&gt;1 : 2 : 3 : []&lt;/code&gt;---that is 1 before 2 before 3 before the empty list.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;:&lt;/code&gt; operator is known as &lt;i&gt;cons&lt;/i&gt;. The list construction in the last paragraph can be thought of as a series of &lt;i&gt;cons cells&lt;/i&gt; (a value &lt;i&gt;consed&lt;/i&gt; onto a list). It could also be written like this, which may make the relation to the list data constructor clearer: &lt;code&gt;1 : (2 : (3 : []))&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;One problem with this representation, though, is that it makes it seem like &lt;code&gt;1&lt;/code&gt; exists &apos;outside&apos; of the list, when it is actually contained by it (and by its  cons cell). Because of how lists are evaluated in Haskell, we&apos;ll see that because the value is contained, we can evaluate cons cells without evaluating their contents.&lt;/p&gt;&lt;p&gt;Let&apos;s talk about spines. You see, the list above can also be represented---conceptually---like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;:
/ \
1   :
 / \
2   :
   / \
  3  []&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In this representation, the cons operators line up to form what is known as the &lt;i&gt;spine&lt;/i&gt;, which is a fancy word for the connective structure that makes up a data structure such as a list or a tree. In the case of lists, it&apos;s just a series of cons operators.&lt;/p&gt;&lt;p&gt;Crucially, &lt;strong&gt;spines are evaluated independently of values&lt;/strong&gt;. What does this mean? Well, functions that only require evaluating the spine and not the values, such as &lt;code&gt;length&lt;/code&gt;, can walk down a list without evaluating the contents. So, returning to our list from before, if we were to apply the &lt;code&gt;length&lt;/code&gt; function on it (and the values hadn&apos;t already been evaluated), you could think of it like this, where the underscores represent values that haven&apos;t been evaluated.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;:
/ \
_   :
 / \
_   :
   / \
  _  []&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Another way to get this point across is to look at what happens when we add bottom values to a list. Run this in the REPL to try it out.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;let&lt;/span&gt; xs = [&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;, undefined, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;]
&lt;span class=&quot;hljs-title&quot;&gt;length&lt;/span&gt; xs &lt;span class=&quot;hljs-comment&quot;&gt;-- 3&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;take&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt; xs &lt;span class=&quot;hljs-comment&quot;&gt;-- [1]&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;take&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; xs &lt;span class=&quot;hljs-comment&quot;&gt;-- Exception: Prelude.undefined&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Taking the length of the list works just fine because we don&apos;t need to evaluate the items in the list. Taking the first element is no problem because it&apos;s a regular value and the rest of the list has not been evaluated. When we take two values, however, this forces the evaluation of the second item in the list, &lt;code&gt;undefined&lt;/code&gt;, which causes the program to crash.&lt;/p&gt;&lt;hr&gt;&lt;p&gt;There is loads more to be said about list evaluation and the impacts it has on what we can and can&apos;t do in code, but these are the most important things covered in this chapter.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Chapter definitions&lt;/h2&gt;&lt;ul&gt;&lt;li&gt;Product type ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;A &lt;i&gt;product type&lt;/i&gt; is a type that contains several other types at the same time. The canonical example is a tuple: You can have a tuple of a &lt;code&gt;Bool&lt;/code&gt; and an &lt;code&gt;Int&lt;/code&gt;, and for every instance you have of that type, you will have both a &lt;code&gt;Bool&lt;/code&gt; &lt;i&gt;and&lt;/i&gt; an &lt;code&gt;Int&lt;/code&gt;. The reason its called a product type is that the number of possible permutations is the product of the number of possible values for each type.&lt;/p&gt;&lt;p&gt;Say you have a data type: &lt;code&gt;data Direction = Up | Down | Left | Right&lt;/code&gt;. If you have a &lt;code&gt;(Bool, Direction)&lt;/code&gt; tuple, you now have $8$ ($4 \cdot 2$) different possible permutations of that tuple.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Sum type ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;A &lt;i&gt;sum type&lt;/i&gt; is a type that is only one of a set number of types at any time. Relating this back to the example above with &lt;code&gt;Bool&lt;/code&gt; and &lt;code&gt;Int&lt;/code&gt;: If you have a data type that is either a &lt;code&gt;Bool&lt;/code&gt; &lt;i&gt;or&lt;/i&gt; an &lt;code&gt;Int&lt;/code&gt; (such as &lt;code&gt;Either Bool Int&lt;/code&gt;), then that&apos;s a sum type. The number of possible permutations is the sum of the number of possible values for each type.&lt;/p&gt;&lt;p&gt;Using the &lt;code&gt;Direction&lt;/code&gt; type from above, &lt;code&gt;Either Bool Direction&lt;/code&gt; has $6$ ($4 + 2$) possible values.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Cons ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;The &lt;code&gt;:&lt;/code&gt; operator. Used to prepend a value onto a list. Can also be used as a verb (e.g. &lt;i&gt;consing a value onto a list&lt;/i&gt;).&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Cons cell ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;A data constructor and a product of the types &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;[a]&lt;/code&gt; as defined in the list data type definition.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Spine ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;A structure that strings a collection of values together, the scaffolding of a data structure. For the list datatype, it&apos;s formed by the recursive nesting of cons cells.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Other topics&lt;/h2&gt;&lt;p&gt;In addition to what we have covered here, the chapter also contains more information about pattern matching on lists, and some common list operations: &lt;code&gt;map&lt;/code&gt;, &lt;code&gt;filter&lt;/code&gt;, and &lt;code&gt;zip&lt;/code&gt;. However, to keep things nice and brief, I&apos;ve decided to leave them out for now. For more information on those topics, please consult your search engine of choice or nearest message board.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Goodbye 2019, Hello 2020]]></title><description><![CDATA[In which I look back upon the year that is about to close and look forward to the year at hand. This post is a summary of what I achieved in 2019 and a list of new goals I've set for myself for 2020.]]></description><link>https://blog.thomasheartman.com/posts/goodbye-2019-hello-2020</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/goodbye-2019-hello-2020</guid><pubDate>Mon, 30 Dec 2019 18:47:30 GMT</pubDate><content:encoded>&lt;p&gt;It&apos;s the end of the year and there&apos;s round-ups and predictions everywhere, so I think it&apos;s an appropriate time to take a step back and look at what I&apos;ve achieved this year and what I have in mind for next year.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;2019&lt;/h2&gt;&lt;p&gt;Let&apos;s move in a chronological fashion. In 2019, my list of goals was just a slightly-longer-than-usual Slack message to my friends. They were pretty vague, but still hold some value as a set of overarching goals.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Goals&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;Containers ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Before 2019, I&apos;d hardly ever touched a container. I&apos;d heard lots about them on various podcasts and was really intrigued. I wanted to &apos;really familiarize myself with the whole thing&apos; (how&apos;s that for a vague goal?).&lt;/p&gt;&lt;p&gt;A year later, do I think I&apos;ve succeeded? &lt;strong&gt;Yes&lt;/strong&gt;. It&apos;s stated in a very unclear fashion and can be taken to mean a lot of things, but since then, I&apos;ve been working pretty closely with containers and Kubernetes pretty much the entire time. Yes, there&apos;s still some things that are unclear to me, but overall, I think I understand containers well enough to have cleared that goal.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;NixOS ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;I installed NixOS on my personal computer pretty much exactly a year ago. It was (and still is) my first real foray into the Linux world. I&apos;d used Ubuntu for some university assignments previously, but that&apos;s it. It took me a good few weeks to get my external monitors up and working, but these days, most everything is running pretty smoothly (except for that NVidia GPU I&apos;ve got ...).&lt;/p&gt;&lt;p&gt;I said that I&apos;d &apos;just got it set up over Christmas, but there is still a lot left to be done and a lot of things to discover.&apos; A year later, I&apos;m fairly comfortable in NixOS, I use Nix for a lot of work related stuff, and I love it. I&apos;d say I&apos;ve finished the NixOS setup and discovered much, though there is still a lot left to be done. What I have achieved is: I have a stable operating system that works as I expect and with a window manager / desktop environment that I enjoy. I&apos;m happy with the OS state of things for now. &lt;strong&gt;Achieved&lt;/strong&gt;.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Give a talk ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Said at the time: &apos;This is something I&apos;ve been wanting to do for a while, and I think this year is the right time, once I&apos;m out of uni and have a bit more time (and experience) on my hands.&apos;&lt;/p&gt;&lt;p&gt;This is probably the one goal I set for myself that is the easiest to measure. I spoke internally at my company about Algebraic Data Types, I held a workshop (still counts) on re-implementing some basic data types and creating opaque types at Oslo Elm Meetup, and I held a talk about the new &lt;code&gt;async/.await&lt;/code&gt; features in Rust at Rust Oslo. &lt;strong&gt;Done&lt;/strong&gt;.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Non-goals&lt;/h3&gt;&lt;p&gt;In addition to the above goals, I also achieved a few other things that I&apos;d like to highlight in this post. These are items that I didn&apos;t put on my to-do list, but that I consider significant enough to mention.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Kubernetes/OpenShift ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;I started working in a team where OpenShift is an important part of the workflow, and interacting with it became a natural part of my day-to-day work.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Started &lt;a href=&quot;https://xkcd.com/148/&quot;&gt;blagging&lt;/a&gt; ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Took me a while, but I finally got going. It&apos;s been a lot of work, but very rewarding.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Became a co-organizer of the &lt;a href=&quot;https://www.meetup.com/Rust-Oslo/&quot;&gt;Rust Oslo Meetup group&lt;/a&gt; ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;I&apos;m excited to see what we can do to further engage the Rust community in the vicinity and what we&apos;ll be doing in the coming year.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;2020&lt;/h2&gt;&lt;p&gt;Looking forward to 2020, what do I want to achieve? What skills do I want to develop? After some thought, I&apos;ve come to the conclusion that my &apos;theme&apos; for 2020&apos;s goals is &lt;i&gt;mastery&lt;/i&gt;. I&apos;ve found tools that I really like and that align with my way of thinking. However, I don&apos;t feel like I&apos;ve fully mastered any of them just yet. Most of my goals will revolve around improving my skill with tools that I already know and love.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Goals&lt;/h3&gt;&lt;p&gt;Here&apos;s a loose definition of my goals for the coming year.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h4&gt;General goals&lt;/h4&gt;&lt;p&gt;These are the general goals that I&apos;m setting for myself. These are the ones I will actively be pursuing and working towards.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;More infrastructure work ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Building on the &apos;containers&apos; goal of this past year, I want to keep working on infrastructure: Kubernetes, CI/CD pipelines, containers, the whole deal. I went through a Red Hat training course this year, working towards a certification as a &apos;Specialist in OpenShift Application Development&apos;. I failed the exam, but learned a lot in the process. Let&apos;s see if I can use that to pass! Apart from that one specific goal, this post is more about making myself familiar with the tools and getting really comfortable with them. You know, &lt;i&gt;mastering&lt;/i&gt; them.&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;More Nix&lt;/dt&gt;&lt;dd&gt;It&apos;s been a year of NixOS, and it&apos;s been great. Now I want to get really comfortable with the difference between &lt;code&gt;build.nix&lt;/code&gt;, &lt;code&gt;default.nix&lt;/code&gt;, &lt;code&gt;shell.nix&lt;/code&gt;, how &lt;code&gt;nix-build&lt;/code&gt; works, etc. Specifically, I&apos;d like to be comfortable with setting up a Haskell dev env with Nix and Cabal.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;More Emacs&lt;/dt&gt;&lt;dd&gt;Emacs has been my go-to editor for a year and a half now, and I still get stuck in weird states sometimes. This coming year, I want to get more comfortable with it on a deeper level. Step one: Read the built-in Emacs manual.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;More community engagement&lt;/dt&gt;&lt;dd&gt;I gave some talks and workshops,  both internally and at local meetups this past year. I want to do more of that in 2020. Also: apply for more conference talks. I applied to a few this past year, but didn&apos;t get any of them.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Programming Language Theory / Compilers&lt;/dt&gt;&lt;dd&gt;I&apos;ve had an interest in type systems and PLT for a while. While writing this post, I realized I should do something about it and ordered &lt;i&gt;Types and Programming Languages&lt;/i&gt; by Benjamin C. Pierce. I don&apos;t know enough about it to set any clear goals just yet, however.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h4&gt;Languages&lt;/h4&gt;&lt;p&gt;While I&apos;m not going into this coming year with any clear language goals in mind, I&apos;d like this to serve as a recording of what languages have me the most curious at the moment. I&apos;m not making any clear commitments to learning any of these, but I think it&apos;s important to keep an open mind and keep exploring new languages and new concepts. As Scott Wlaschin talks about in his talk &lt;i&gt;[[https://fsharpforfunandprofit.com/fourfromforty/][Four Languages from Forty Years Ago]]&lt;/i&gt;, you should look for languages that expand your mind and help you think about problems in a new way. He awards languages that achieve this a &apos;Galaxy Brain Seal of Approval&apos;. There is an Alan Perlis quote in the slides saying that &apos;A language that doesn&apos;t affect the way you think about programming, is not worth knowing&apos;.&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Haskell&lt;/dt&gt;&lt;dd&gt;Yeah, I&apos;ve been doing a bit of this, but not enough. I&apos;ve got the basics down, but I need to put it into practice. I want to build something; a simple Web API or command line interface should be enough.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Lisp&lt;/dt&gt;&lt;dd&gt;Doesn&apos;t matter whether it&apos;s common lisp, scheme, (typed) racket, or clojure: I want to get comfortable with lisp. If nothing else, at least it&apos;ll help me configure Emacs.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Elixir&lt;/dt&gt;&lt;dd&gt;This is the wildcard on the list. I have not really looked much at it at all, but I hear great things. Should offer some nice Galaxy Brain moments.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;SMART goals&lt;/h3&gt;&lt;p&gt;The goals listed above are generally quite vague, and it&apos;d be hard to say for sure whether I&apos;ve achieved them or not. To make them more actionable, let&apos;s create a set of &lt;i&gt;SMART&lt;/i&gt; goals that I can tick. What are SMART goals? Of course, &lt;a href=&quot;https://www.wikiwand.com/en/SMART_criteria&quot;&gt;Wikipedia has an article on it&lt;/a&gt;, but the short version is that SMART is an acronym that stands for &apos;Specific, Measurable, Achievable, Relevant, Time-bound&apos;. Organized by topic, this is my list:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Programming Language Theory ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;I don&apos;t have enough insight into this to make any clear goals for it, but I&apos;ve had a brief look at the &lt;i&gt;Types and Programming Languages&lt;/i&gt; book. It&apos;s about 650 pages long. I&apos;d say I should get through it by July at latest. In short: Read &lt;i&gt;Types and Programming Languages&lt;/i&gt; by July.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Community engagement ::&lt;/li&gt;&lt;ul&gt;&lt;li&gt;Give at least three talks/workshops at community events.&lt;/li&gt;&lt;li&gt;Apply as a speaker to at least three conferences.&lt;/li&gt;&lt;/ul&gt;&lt;li&gt;Emacs ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;By February 1^st, I want to have gotten through the Emacs manual. At this point, I may decide to try and (at least start to) configure Emacs from the ground up (rather than relying on Spacemacs), but that is not a requirement.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Nix ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Write about what the various &lt;code&gt;.nix&lt;/code&gt; files are and what their intended use is. Should discuss at least &lt;code&gt;build.nix&lt;/code&gt;, &lt;code&gt;default.nix&lt;/code&gt;, and &lt;code&gt;shell.nix&lt;/code&gt;.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;OpenShift ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Pass the &lt;a href=&quot;https://www.redhat.com/en/services/training/ex288-red-hat-certified-specialist-openshift-application-development-exam&quot;&gt;Red Hat Certified Specialist in OpenShift Application Development exam&lt;/a&gt;.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Containers / Infrastructure / Haskell / Nix ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;This is a set of goals that apply to broad range of topics. I want to manage a Kubernetes cluster somewhere and create a Haskell API that serves requests. The Haskell project should use Nix for as much as practically possible. What sort of data the API serves doesn&apos;t matter.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Deadlines&lt;/strong&gt;:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;April 1^st&lt;/dt&gt;&lt;dd&gt;Have Kubernetes cluster up and running.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;June 1^st&lt;/dt&gt;&lt;dd&gt;Have the Haskell API up and running.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;hr&gt;&lt;p&gt;And that&apos;s what I&apos;m planning to look into in the coming year. As always: plans change, life happens, and things inevitably don&apos;t go as expected, but it&apos;s nice to have a little something to look back on, at least. What do you think? Do you have any clear goals?&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Let's read: Haskell Programming from First Principles, pt VIII]]></title><description><![CDATA[In which we talk about recursion and play with bottoms. We look at defining functions in terms of themselves, applying a function an arbitrary number of times, and what base cases are.]]></description><link>https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-viii</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-viii</guid><pubDate>Mon, 23 Dec 2019 08:37:31 GMT</pubDate><content:encoded>&lt;p&gt;Taking a step back from a pretty dense chapter on more functional patterns, this time we&apos;re looking specifically at &lt;i&gt;one&lt;/i&gt; thing: recursion. Chapter 8 of the book covers this in pretty good detail, giving a fairly wide range of examples, but I&apos;ll be trying to distill it down to its essence in this post. Let&apos;s start at the very beginning, why don&apos;t we?&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;What is recursion?&lt;/h2&gt;&lt;p&gt;A recursive function is---in its simplest terms---a function which calls itself. As the book describes it: &quot;recursion is defining a function in terms of itself via self-referential expressions.&quot; This means that until some condition is met, the function will keep calling itself. If this condition is never met, the function never terminates. Recursion is an important concept in Haskell, because it gives us a way to express &lt;i&gt;indefinite&lt;/i&gt; computations.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Base cases&lt;/h3&gt;&lt;p&gt;To reiterate: given that it terminates, a recursive function is a function that will keep calling itself until some condition to stop recursing is met. This condition is often known as the &lt;i&gt;base case&lt;/i&gt;. For instance, let&apos;s look at writing a factorial function, which is a function that multiplies all positive integers (${1..n}$) up to and including the number we&apos;re calculating for. In maths, it&apos;s commonly written using an exclamation point, such as $4!$.&lt;/p&gt;&lt;p&gt;So we&apos;re all on the same page about what the function should do, $4!$ is evaluated as $4 \cdot 3 \cdot 2 \cdot 1$, which is equal to $24$.&lt;/p&gt;&lt;p&gt;To make this a recursive function, we know that for any number $n$ greater than one, it is the result of the factorial of $n-1$ multiplied by $n$. In other words, for $n$ greater than one, $n! = n \cdot (n-1)!$. If $n$ is $1$, then $n! = 1$. In our case, the function is not defined for integers less than one.&lt;/p&gt;&lt;p&gt;Based on the little analysis above, we now know that the value of $n!$ is recursively dependent on the value of $(n-1)!$ and so on. We have also identified our base case: $1$. So how would we go about writing this out? How about something like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;factorial&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;Integral&lt;/span&gt; a =&gt; a -&gt; a
&lt;span class=&quot;hljs-title&quot;&gt;factorial&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt; = &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;factorial&lt;/span&gt; n = n * factorial (n - &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;)&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note that this function does not terminate if applied to a value less than $1$. This is an issue that we&apos;ll come back to shortly.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Recursion as indefinite function composition&lt;/h3&gt;&lt;p&gt;One thing that the book mentions that I found quite interesting, is that you can think of recursion as indefinite function composition. When composing functions, all we do is pipe the output of one function into another function. Recursion is the same thing, except it&apos;s always the same function. We can use this to create functions that will get applied an arbitrary number of times. Indeed, taking it a step further, we can write a function that takes a function, an argument, and the number of times to apply it, and then applies the function the set number of times:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;applyNTimes&lt;/span&gt; :: (&lt;span class=&quot;hljs-type&quot;&gt;Integral&lt;/span&gt; a) =&gt; a -&gt; (b -&gt; b) -&gt; b -&gt; b
&lt;span class=&quot;hljs-title&quot;&gt;applyNTimes&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; _ b = b
&lt;span class=&quot;hljs-title&quot;&gt;applyNTimes&lt;/span&gt; n f b = f . applyNTimes (n - &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;) f $ b&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Using this, we can create an &lt;code&gt;increment&lt;/code&gt; function:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;increment&lt;/span&gt; :: (&lt;span class=&quot;hljs-type&quot;&gt;Integral&lt;/span&gt; a, &lt;span class=&quot;hljs-type&quot;&gt;Num&lt;/span&gt; b) =&gt; a -&gt; b -&gt; b
&lt;span class=&quot;hljs-title&quot;&gt;increment&lt;/span&gt; times = applyNTimes times (+&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;)
&lt;span class=&quot;hljs-comment&quot;&gt;-- increment 5 2 = 7&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;A contrived example, but it&apos;s a pretty cool effect!&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Bottom&lt;/h2&gt;&lt;p&gt;I mentioned when talking about the factorial function that it doesn&apos;t terminate for every possible value we can apply it to. A function that never terminates is one of the ways we can play with bottoms in Haskell (and no, it&apos;s not a kinky as it sounds!).&lt;/p&gt;&lt;p&gt;In Haskell, &lt;i&gt;bottom&lt;/i&gt; (symbolically: &lt;code&gt;⊥&lt;/code&gt;) is used to refer to computations that do not result in a value. The two main varieties of bottom are computations that fail with an error (partial functions) and computations that fail to terminate (such as with infinite recursion and the factorial example above). When you can, &lt;strong&gt;stay away from bottom&lt;/strong&gt;.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Definitons&lt;/h2&gt;&lt;p&gt;This chapter only comes with a single definition: &lt;i&gt;recursion&lt;/i&gt;. The funny thing would be to tell you to start from the top, but let&apos;s be boring and do it the proper way:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Recursion&lt;/dt&gt;&lt;dd&gt;&lt;i&gt;Recursion&lt;/i&gt; is a means of computing results that may require an indefinite amount of work to obtain through the use of repeated function application. A recursive function will usually have at least one case that calls itself and a base case that stops the recursion.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Let's read: Haskell Programming from First Principles, pt VIIc]]></title><description><![CDATA[In which we talk about function composition and pointfree style and cover the chapter definitions for chapter 7. Function composition is especially important and a cornerstone of Haskell programming, so make sure not to miss this one!]]></description><link>https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-viic</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-viic</guid><pubDate>Mon, 16 Dec 2019 22:57:22 GMT</pubDate><content:encoded>&lt;p&gt;Hey, and welcome back to the third and final part of chapter 7 of &lt;i&gt;Haskell Programming From First Principles&lt;/i&gt;! Today we&apos;ll be looking at function composition and pointfree style; two related topics that are very commonly seen in Haskell.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Function composition&lt;/h2&gt;&lt;p&gt;Let&apos;s start of with function composition. Function composition allows us to create new functions by combining existing ones. The one criterion for composing two functions is that the return value (range) of the first function matches the input value (domain) of the second function. In Haskell, we use the dot operator (&lt;code&gt;.&lt;/code&gt;) to compose two functions.&lt;/p&gt;&lt;p&gt;Let&apos;s inspect the type signature of the &lt;code&gt;.&lt;/code&gt; operator and see if we can unpack it:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;(.) :: (b -&gt; c) -&gt; (a -&gt; b) -&gt; a -&gt; c&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;At first, this may seem a bit complicated, so let&apos;s break it down. The &lt;code&gt;.&lt;/code&gt; operator goes between two functions (like this: &lt;code&gt;f . g&lt;/code&gt;) and returns a function that goes from &lt;code&gt;a&lt;/code&gt; to &lt;code&gt;c&lt;/code&gt;. What it does is to simply &apos;glue&apos; the two provided functions together.&lt;/p&gt;&lt;p&gt;I quite like &lt;a href=&quot;http://scottwlaschin.com/&quot;&gt;Scott Wlaschin&lt;/a&gt;&apos;s explanation of it from his talk &lt;a href=&quot;https://youtu.be/WhEkBCWpDas?t=646&quot;&gt;The Power of Composition&lt;/a&gt; (this link takes you to the point in the talk that talks about gluing together functions, but I highly recommend checking out the whole thing if you&apos;re interested), where he talks about gluing together a transformation from an apple to a banana, and a function from a banana to a cherry to create a function from an apple to a cherry.&lt;/p&gt;&lt;p&gt;The simplest way to explain composition may be to say that you perform an operation on a value, and then pass the result of that operation to the next function. That new function which puts those two together is the composed function. You might see an example like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;(f . g) x = f (g x)&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This tells us that applying &lt;code&gt;f&lt;/code&gt; composed with &lt;code&gt;g&lt;/code&gt; to &lt;code&gt;x&lt;/code&gt; is the same as applying &lt;code&gt;g&lt;/code&gt; to the argument &lt;code&gt;x&lt;/code&gt; and then applying &lt;code&gt;f&lt;/code&gt; to the result of that. Note that the &lt;code&gt;.&lt;/code&gt; operator might initially appear to read backwards: It&apos;s the last function to get run that gets written out first. This is because of it&apos;s mathematical roots, where people use the &apos;∘&apos; symbol for composing functions (so our &lt;code&gt;f . g&lt;/code&gt; would be $f ∘ g$). I suggest reading the symbol as &apos;after&apos;, which makes it &apos;f after g&apos;, for instance.&lt;/p&gt;&lt;p&gt;If this is all a bit abstract and jargon-y, why don&apos;t we look at a concrete example. Say we want a function that tells us whether a string is of even length or not. In that case, we can express the full function as a composition of two smaller functions (the signatures have been simplified/specialized for the sake of example; check the REPL for more): &lt;code&gt;even :: Int -&gt; Bool&lt;/code&gt;, and &lt;code&gt;length :: String -&gt; Int&lt;/code&gt;  (so it&apos;d be &apos;&lt;code&gt;even&lt;/code&gt; after &lt;code&gt;length&lt;/code&gt;&apos;). Notice that the return type of &lt;code&gt;length&lt;/code&gt; matches the input type of &lt;code&gt;even&lt;/code&gt;, and that the type of &lt;code&gt;isOfEvenLength&lt;/code&gt; matches the combination of the functions.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;isOfEvenLength&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;isOfEvenLength&lt;/span&gt; = even . length&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The astute reader (that&apos;s you!) might notice that the function we defined as the composition of the other two functions (&lt;code&gt;isOfEvenLength&lt;/code&gt;) doesn&apos;t list any arguments in its definition. This might look strange but it takes us nicely into our next point: pointfree style.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Pointfree style&lt;/h2&gt;&lt;p&gt;Pointfree style is a way of writing functions without specifying their arguments, most notably when working with composition. It&apos;s called &apos;pointfree&apos; because the arguments are also known as &apos;points&apos;. There are arguments both for and against writing pointfree style, and it&apos;s true that excessive use may cause code to become harder to understand, but used sensibly it can make code tidier, cleaner, and let&apos;s us put the focus on the transformations, the functions, rather than the data supplied to them.&lt;/p&gt;&lt;p&gt;Using one of the examples from before, we now get:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;(f . g) x = f (g x)
&lt;span class=&quot;hljs-comment&quot;&gt;-- the above now becomes&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt; . g = \x -&gt; f (g x)

&lt;span class=&quot;hljs-comment&quot;&gt;-- similarly, we can add more functions&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt; . g . h = \x -&gt; f (g (h x))&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;How does this work? Well, it all goes back to the lambda calculus and currying. Let&apos;s take a step back and look at how you could write an alias for a function in Haskell:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt; a b = &lt;span class=&quot;hljs-comment&quot;&gt;-- ... implementation&lt;/span&gt;

&lt;span class=&quot;hljs-title&quot;&gt;g&lt;/span&gt; = f&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In the above code, we have defined &lt;code&gt;g&lt;/code&gt; as simply being the same as &lt;code&gt;f&lt;/code&gt;. We&apos;ll still need to provide it with the same arguments (&lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt;), but it&apos;s just given a different name. If we want to, we can choose to define it as a specialized version of &lt;code&gt;f&lt;/code&gt;, with the first argument already applied:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt; a b = &lt;span class=&quot;hljs-comment&quot;&gt;-- ... implementation&lt;/span&gt;

&lt;span class=&quot;hljs-title&quot;&gt;g&lt;/span&gt; = f &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In this case, &lt;code&gt;g&lt;/code&gt; is a partially applied version of &lt;code&gt;f&lt;/code&gt; and is a function from one argument to a result (whatever &lt;code&gt;f&lt;/code&gt; returns). We could also write the above as &lt;code&gt;g x = f 2 x&lt;/code&gt;, but because of how partial application works, there&apos;s no need to do this. We&apos;ve already said that &lt;code&gt;g&lt;/code&gt; is the same as &lt;code&gt;f&lt;/code&gt; applied to &lt;code&gt;2&lt;/code&gt;, and that naturally returns a function from one argument to the result.&lt;/p&gt;&lt;p&gt;Similarly, we might do it for something like &lt;code&gt;map&lt;/code&gt;. Say we want a function that doubles all values in a list:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;doubleVals&lt;/span&gt; = map (*&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;)
&lt;span class=&quot;hljs-comment&quot;&gt;-- is the same as&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;doubleVals&lt;/span&gt; xs = map (*&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;) xs&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The two definitions above are equivalent, they&apos;re just written out differently.&lt;/p&gt;&lt;p&gt;Whether you prefer pointfree or &apos;pointful&apos; styles is an individual thing, and is probably based on experience and circumstance. As mentioned earlier, too much and it makes your code hard to read, too little and you&apos;re writing out way more than what you need to and taking focus away from the important parts. Like with so many things, try and apply the &lt;a href=&quot;https://www.wikiwand.com/en/Goldilocks_principle&quot;&gt;Goldilocks principle&lt;/a&gt;. As always, the &lt;a href=&quot;https://wiki.haskell.org/Pointfree&quot;&gt;Haskell wiki&lt;/a&gt; has more detailed information on the topic, so go give that a read if you fancy.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Definitions&lt;/h2&gt;&lt;p&gt;As it&apos;s the last post for this chapter, let&apos;s go over the chapter definitions.&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Anonymous function&lt;/dt&gt;&lt;dd&gt;Often known as a &lt;i&gt;lambda&lt;/i&gt;. It is a function that isn&apos;t bound to an identifier and is instead just used as an argument to another function or the like. For instance, &lt;code&gt;\x -&gt; x&lt;/code&gt; is an anonymous version of the &lt;code&gt;id&lt;/code&gt; function (&lt;code&gt;id x = x&lt;/code&gt;).&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Currying&lt;/dt&gt;&lt;dd&gt;The act of transforming a function which takes multiple arguments to a series of nested functions that each take a single argument and return the next function in line (or the result if we&apos;re at the end). In Haskell, every function is curried, and this is baked into the language so you don&apos;t have to worry about it.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Pattern matching&lt;/dt&gt;&lt;dd&gt;A way to deconstruct various data types to do something with---or based on---their contents.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Bottom&lt;/dt&gt;&lt;dd&gt;&lt;i&gt;Bottom&lt;/i&gt; is a non-value used to denote  that a program cannot return a value or a result. A simple example would be an infinitely looping function, but values that don&apos;t handle all their inputs and throw errors also apply here. We&apos;ll talk more about &lt;i&gt;Bottom&lt;/i&gt; in the chapter on non-strictness.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Higher-order functions&lt;/dt&gt;&lt;dd&gt;Functions that take other functions as arguments or return functions themselves.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Composition&lt;/dt&gt;&lt;dd&gt;A way of gluing together multiple functions such that each each function is applied to the result of the next function. Creates a pipeline of transformations.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Pointfree&lt;/dt&gt;&lt;dd&gt;Also known as &apos;tacit programming&apos;. Programming without mentioning arguments explicitly.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Let's read: Haskell Programming from First Principles, pt VIIb]]></title><description><![CDATA[In which we look at higher order functions and guards. We look at what the definition of a higher order function is and look at some examples. We also look at guards; what they are, the syntax, and the importance of ordering.]]></description><link>https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-viib</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-viib</guid><pubDate>Mon, 09 Dec 2019 10:30:01 GMT</pubDate><content:encoded>&lt;p&gt;Continuing our foray into the &lt;i&gt;More Functional Patterns&lt;/i&gt; chapter, today we&apos;re looking at higher-order functions and guards.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Higher-order functions&lt;/h2&gt;&lt;p&gt;First off, let&apos;s establish some common ground and agree on the definition. According to &lt;a href=&quot;https://www.wikiwand.com/en/Higher-order_function&quot;&gt;Wikipedia&lt;/a&gt; and the &lt;a href=&quot;https://wiki.haskell.org/Higher_order_function&quot;&gt;Haskell wiki&lt;/a&gt;, a higher-order function is a function that takes other functions as arguments or returns a function as a result. In essence, it&apos;s a function that operates on functions as values. Because functions are just any other value in haskell&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;, this comes very naturally to the language.&lt;/p&gt;&lt;p&gt;So to qualify as a higher-order function, a function must fulfill one of two criteria:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Accept a function as a parameter ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;code&gt;map&lt;/code&gt; and sorting functions are great examples of this. For instance, &lt;code&gt;map&lt;/code&gt;&apos;s signature is &lt;code&gt;map :: (a -&gt; b) -&gt; [a] -&gt; [b]&lt;/code&gt;, where the first parameter is the function used to transform the values of type &lt;code&gt;a&lt;/code&gt; in the list to values of type &lt;code&gt;b&lt;/code&gt;. Sorting functions could take a comparison function (&lt;code&gt;a -&gt; a -&gt; Ordering&lt;/code&gt;) and a list (&lt;code&gt;[a]&lt;/code&gt;), sort the list for you and return the sorted list.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Return a function ::&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;This probably happens more than you realize. Any function that accepts more than one argument in Haskell is by default a higher-order function due to how the lambda calculus works. That said, you can also explicitly return a partially applied function based on the input arguments. For instance, this example takes a boolean value saying whether the function should return a partially applied multiplication or addition, and the first argument to apply to the calculation. It returns the partially applied function:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;Num&lt;/span&gt; a =&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt; -&gt; a -&gt; (a -&gt; a)
&lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt; multiply n =
  &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; multiply &lt;span class=&quot;hljs-keyword&quot;&gt;then&lt;/span&gt;
    (n*)
  &lt;span class=&quot;hljs-keyword&quot;&gt;else&lt;/span&gt;
    (n+)&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;It&apos;s a silly example, but it gets the point across.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Guards&lt;/h2&gt;&lt;p&gt;Next up, the book returns to a form of pattern matching by introducing &lt;i&gt;guards&lt;/i&gt;, which allow us to run code conditionally based on the truth of a statement. If you think that sounds a lot like an &lt;code&gt;if-then-else&lt;/code&gt; expression, that&apos;s because it works pretty much the same but with some different syntax. We&apos;ll run through a couple of different examples to examine the various features that are introduced.&lt;/p&gt;&lt;p&gt;The basic syntax looks like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;myAbs&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;Integer&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Integer&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;myAbs&lt;/span&gt; x
  | x &amp;#x3C; &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;     = (-x)
  | otherwise =   x&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This function has two &lt;i&gt;guards&lt;/i&gt;, each beginning with a pipe symbol (&lt;code&gt;|&lt;/code&gt;). Note that we don&apos;t need an equals sign after the arguments in the first line of the definition; instead, the symbol comes after each respective guard. The first of the guards that evaluates to &lt;code&gt;True&lt;/code&gt; will be executed.&lt;/p&gt;&lt;p&gt;In this function, we have two cases: One for when the value of &lt;code&gt;x&lt;/code&gt; is negative (in which case we&apos;ll return the absolute value of &lt;code&gt;x&lt;/code&gt;), and one for every other case. In the above example, we have used the word &lt;code&gt;otherwise&lt;/code&gt;, which is a synonym for &lt;code&gt;True&lt;/code&gt;, as a catch-all for every other case.&lt;/p&gt;&lt;p&gt;If we want to explicitly enumerate all options, we can do that too:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;myAbs&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;Integer&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Integer&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;myAbs&lt;/span&gt; x
  | x &amp;#x3C;  &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; = (-x)
  | x &gt;= &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; =   x&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This will work the exact same as the previous version, but in this case we&apos;re handling all cases explicitly. When explicitly listing all options, make sure you have enabled warnings (or errors) for non-exhaustive patterns to avoid accidentally partial functions.&lt;/p&gt;&lt;p&gt;What if we want to share some values between the different guards? We can use &lt;code&gt;where&lt;/code&gt;-statements for that! Imagine a function that takes the lengths of the two legs (catheti) of a right triangle and returns whether the triangle is big, small, or medium based on the length of the hypotenuse:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;triangleSize&lt;/span&gt; :: (&lt;span class=&quot;hljs-type&quot;&gt;Floating&lt;/span&gt; a, &lt;span class=&quot;hljs-type&quot;&gt;Ord&lt;/span&gt; a) =&gt; a -&gt; a -&gt; &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;triangleSize&lt;/span&gt; c1 c2
  | h &gt;= &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;Big triangle&quot;&lt;/span&gt;
  | h &gt;= &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;Medium triangle&quot;&lt;/span&gt;
  | h &amp;#x3C;  &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;Small triangle&quot;&lt;/span&gt;
  &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt; h = sqrt (c1^&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; + c2^&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;)&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;When declaring variables like this, they&apos;re in scope for all of the guards.&lt;/p&gt;&lt;p&gt;This last example also demonstrates the importance of order on the guards. Because only the first guard that evaluates to &lt;code&gt;True&lt;/code&gt; is executed, the above function works as expected. If we switched the two guards for big and medium triangles, no triangle would ever be considered &apos;big&apos;. What a sad world that would be.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Next up&lt;/h2&gt;&lt;p&gt;That was all we had time for today, my dear reader. We still have a little bit left of this chapter: function composition and pointfree style. Two very interesting topics which I&apos;m looking forward to covering next time. Until then: take care!&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;p&gt;&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt; You may have heard the term &apos;first-class functions&apos;. This is what that means. You can pass functions around like any other variable, store them in data structures, assign them to variables, and so forth. See &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function&quot;&gt;MDN&lt;/a&gt; or &lt;a href=&quot;https://www.wikiwand.com/en/First-class_function&quot;&gt;Wikipedia&lt;/a&gt; for more.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Let's read: Haskell Programming from First Principles, pt VIIa]]></title><description><![CDATA[In which we start looking at the 'More Functional Patterns' chapter of 'Programming Haskell From First Principles'. This time, we're looking at pattern matching and case expressions; what they are and how to use them.]]></description><link>https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-viia</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-viia</guid><pubDate>Mon, 02 Dec 2019 22:39:31 GMT</pubDate><content:encoded>&lt;p&gt;We&apos;ve reached chapter 7: &lt;i&gt;More Functional Patterns&lt;/i&gt;. This is a pretty big chapter that covers a lot of ground, so to make it more digestible to you (and more manageable to me), I&apos;m going to break this chapter up into multiple pieces. In this post, we&apos;ll be looking at pattern matching and case expressions. Later posts will cover higher-order functions, function composition, and pointfree style, so there&apos;s lots to look forward to!&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Pattern matching&lt;/h2&gt;&lt;p&gt;&quot;Pattern matching is an integral and ubiquitous feature of Haskell&quot;. Thus opens the sub-chapter on pattern matching. If you&apos;ve seen any amount of Haskell code, you&apos;ve probably come across it, but in case you haven&apos;t (and if you have: just to make sure we&apos;re on the same page), here&apos;s a primer.&lt;/p&gt;&lt;p&gt;Pattern matching is a way for us to match values against certain &apos;patterns&apos;. Depending on the context, a pattern can be a wide range of things, including specific strings, numeric literals and list syntax; pattern matching can match on &lt;i&gt;any and all&lt;/i&gt; data constructors. Pattern matching can even let us match on the inner structure of the thing we&apos;re matching on, such as a list or a tuple. Let&apos;s have some examples.&lt;/p&gt;&lt;p&gt;We can check whether a provided &lt;code&gt;Integer&lt;/code&gt; is of a specific value, like in the following case:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;isTheAnswer&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;Integer&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;isTheAnswer&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;42&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;isTheAnswer&lt;/span&gt; _ = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can check whether  a list contains zero, one, or many elements:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;listState&lt;/span&gt; :: [a] -&gt; &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;listState&lt;/span&gt; [] = &lt;span class=&quot;hljs-string&quot;&gt;&quot;The list is empty&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;listState&lt;/span&gt; [_] = &lt;span class=&quot;hljs-string&quot;&gt;&quot;The list has one element&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;listState&lt;/span&gt; (_:_:_) = &lt;span class=&quot;hljs-string&quot;&gt;&quot;The list has at least two elements&quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can also check which data constructor has been used to create a value and extract the constructor parameters from it or even check them for specific values:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;User&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;LoggedIn&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt; | &lt;span class=&quot;hljs-type&quot;&gt;Anonymous&lt;/span&gt;&lt;/span&gt;

&lt;span class=&quot;hljs-title&quot;&gt;userInfo&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;User&lt;/span&gt; -&gt; &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;userInfo&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Anonymous&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;The user is anonymous&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;userInfo&lt;/span&gt; (&lt;span class=&quot;hljs-type&quot;&gt;LoggedIn&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&quot;admin&quot;&lt;/span&gt;) = &lt;span class=&quot;hljs-string&quot;&gt;&quot;The user is an administrator&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;userInfo&lt;/span&gt; (&lt;span class=&quot;hljs-type&quot;&gt;LoggedIn&lt;/span&gt; username) = &lt;span class=&quot;hljs-string&quot;&gt;&quot;The user is &quot;&lt;/span&gt; ++ username&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This covers some of the patterns you might see used with pattern matching. Keep in mind that the order of the patterns matter: they are evaluated from top to bottom, and once a pattern matches, no more cases will get checked.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Covering all the cases&lt;/h3&gt;&lt;p&gt;When pattern matching, you should always handle all cases to avoid partial functions. This might seem like a hassle, but you don&apos;t need to handle all the cases explicitly. As seen in the first example (&lt;code&gt;isTheAnswer&lt;/code&gt;), the &lt;code&gt;_&lt;/code&gt; pattern works as a catch-all, meaning that if no other patterns have matched yet, this will match anything.&lt;/p&gt;&lt;p&gt;In addition to just being vigilant about matching all possible combinations, you can also turn up the compiler&apos;s crankiness by using the &lt;code&gt;-Wall&lt;/code&gt; flag. This will give you warnings if your patterns are non-exhaustive.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Case expressions (or: more pattern matching)&lt;/h2&gt;&lt;p&gt;Similarly to the pattern matching above, we also have &lt;code&gt;case&lt;/code&gt; expressions in Haskell. They work the same way as basic pattern matching, but the syntax is a bit different. In short, it gives you all the power that you get from pattern matching, but with a bit more syntax. Let&apos;s rewrite the &lt;code&gt;listState&lt;/code&gt; function above using a case expression to see the similarities:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;listState&lt;/span&gt; :: [a] -&gt; &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;listState&lt;/span&gt; xs =
  &lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; xs &lt;span class=&quot;hljs-keyword&quot;&gt;of&lt;/span&gt;
    [] -&gt; &lt;span class=&quot;hljs-string&quot;&gt;&quot;The list is empty&quot;&lt;/span&gt;
    [_] -&gt; &lt;span class=&quot;hljs-string&quot;&gt;&quot;The list has one element&quot;&lt;/span&gt;
    (_:_:_) -&gt; &lt;span class=&quot;hljs-string&quot;&gt;&quot;The list has at least two elements&quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This looks very much like pattern matching (and serves the same purpose in this case), except that we use the &lt;code&gt;case ... of&lt;/code&gt; structure to match on a named variable instead of directly on an input. Which is more appropriate depends on your use case and preferences.&lt;/p&gt;&lt;hr&gt;&lt;p&gt;And that&apos;s it for today, kids. A shorter, more digestible format that covers only the most essential. I&apos;ll cover the rest of the chapter in this way, and then we&apos;ll see what works best moving forward. Next time: higher-order functions! Until then: take care!&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Async Rust: async main]]></title><description><![CDATA[In which I expand a little bit upon async functionality in Rust, introducing attributes that allow you to run async functions in your main function.]]></description><link>https://blog.thomasheartman.com/posts/async-rust-async-main</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/async-rust-async-main</guid><pubDate>Mon, 25 Nov 2019 21:17:59 GMT</pubDate><content:encoded>&lt;p&gt;In &lt;a href=&quot;https://blog.thomasheartman.com/posts/async-rust/&quot;&gt;the previous post&lt;/a&gt; we had an introductory glance at &lt;code&gt;async/.await&lt;/code&gt; in Rust, looking at what it does and how you&apos;d use it. However, the little bit of code we were left with at the end still felt a bit rough. Coming from languages where you can have an async &lt;code&gt;main&lt;/code&gt; function (or at least one that lets you act as if it is), it felt like an extra hurdle to have to extract all async functionality out into a separate function.&lt;/p&gt;&lt;p&gt;Luckily, Reddit user &lt;a href=&quot;https://www.reddit.com/user/mbuesing/&quot;&gt;mbuesing&lt;/a&gt; &lt;a href=&quot;https://www.reddit.com/r/rust/comments/dyat19/async_rust_a_gentle_introduction/f813vqi?utm_source=share&amp;#x26;utm_medium=web2x&quot;&gt;pointed out&lt;/a&gt; that there is an attribute available in async-std that you can use to make your &lt;code&gt;main&lt;/code&gt; function asynchronous: &lt;code&gt;async_std::main&lt;/code&gt;! Let&apos;s have a look at what changes we&apos;d have to make to incorporate that.&lt;/p&gt;&lt;p&gt;First off, let&apos;s update the &lt;code&gt;Cargo.toml&lt;/code&gt; file. It&apos;s mostly the same as last time, but we&apos;re going to have to add the &quot;attributes&quot; feature from async-std:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-toml&quot;&gt;&lt;span class=&quot;hljs-section&quot;&gt;[package]&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;name&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;async-basics&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;version&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;0.1.0&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;authors&lt;/span&gt; = [&lt;span class=&quot;hljs-string&quot;&gt;&quot;Your Name &amp;#x3C;your.email@provider.tld&gt;&quot;&lt;/span&gt;]
&lt;span class=&quot;hljs-attr&quot;&gt;edition&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;2018&quot;&lt;/span&gt;

&lt;span class=&quot;hljs-section&quot;&gt;[dependencies]&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;async-std&lt;/span&gt; = { version = &lt;span class=&quot;hljs-string&quot;&gt;&quot;1&quot;&lt;/span&gt;, features = [&lt;span class=&quot;hljs-string&quot;&gt;&quot;attributes&quot;&lt;/span&gt;] }
&lt;span class=&quot;hljs-attr&quot;&gt;surf&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;1&quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next up, let&apos;s update the &lt;code&gt;main.rs&lt;/code&gt; file. If we&apos;re doing everything within the &lt;code&gt;main&lt;/code&gt; function, we can cut it down to about 8 lines of code, compared to the 14 lines we had last time, and because it&apos;s such a simple program, it&apos;s not any less readable:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;use&lt;/span&gt; surf;

&lt;span class=&quot;hljs-meta&quot;&gt;#[async_std::main]&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
    &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; surf::get(&lt;span class=&quot;hljs-string&quot;&gt;&quot;https://pokeapi.co/api/v2/move/surf&quot;&lt;/span&gt;).recv_string().&lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; {
        &lt;span class=&quot;hljs-literal&quot;&gt;Ok&lt;/span&gt;(s) =&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;Fetched results: {:#?}&quot;&lt;/span&gt;, s),
        &lt;span class=&quot;hljs-literal&quot;&gt;Err&lt;/span&gt;(e) =&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;Got an error: {:?}&quot;&lt;/span&gt;, e),
    };
}&lt;/code&gt;&lt;/pre&gt;&lt;hr&gt;&lt;p&gt;So there you have it. With some extra attributes, we can make async code pretty ergonomic in Rust. Now, let&apos;s make something cool!&lt;/p&gt;</content:encoded></item><item><title><![CDATA[Async Rust]]></title><description><![CDATA[In which we explore Rust's newly stabilized async/.await language feature by creating a simple, asynchronous application. We look at what you need to do asynchronous programming in Rust and how it differs from other languages. And we talk a little bit about Pokémon!]]></description><link>https://blog.thomasheartman.com/posts/async-rust</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/async-rust</guid><pubDate>Mon, 18 Nov 2019 08:21:10 GMT</pubDate><content:encoded>&lt;p&gt;Hot off the heels of RustFest Barcelona and the stabilization of &lt;code&gt;async/.await&lt;/code&gt;, I think it&apos;s safe to say that one of Rust&apos;s most anticipated language features has finally landed. And for that occasion (and because I&apos;ve had some trouble understanding certain bits of it myself), I wanted to write a little introduction to asynchronous programming in Rust. We&apos;ll be creating a super simple application that fetches some data from the internet using the our newfound &lt;code&gt;async&lt;/code&gt; abilities. The stabilization of &lt;code&gt;async/.await&lt;/code&gt; also coincides nicely with another event I&apos;m excited about: This week saw the release of the most recent entries in the mainline Pokémon games, &lt;a href=&quot;https://bulbapedia.bulbagarden.net/wiki/Pok%25C3%25A9mon_Sword_and_Shield&quot;&gt;Pokémon Sword and Shield&lt;/a&gt;, and because I&apos;m a bit too busy to pick them up just yet, I&apos;ll make do by fetching data from the &lt;a href=&quot;https://pokeapi.co/&quot;&gt;PokéAPI&lt;/a&gt; for now.&lt;/p&gt;&lt;p&gt;I&apos;m assuming some base knowledge of Rust&apos;s syntax and ecosystem, but I hope that this is pretty accessible even to people very new to the community.&lt;/p&gt;&lt;p&gt;But before diving into the coding part, let&apos;s cover some basic concepts of asynchronous programming and how it might be a bit different in Rust than what you&apos;d expect.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;What does &lt;code&gt;async&lt;/code&gt; mean?&lt;/h2&gt;&lt;p&gt;In Rust, when we talk about &lt;code&gt;async&lt;/code&gt;, we&apos;re talking about running code concurrently, or having multiple overlapping (in time) computations run on a single thread. Multithreading is a related, but distinct concept. Multithreading is ideal for when you&apos;ve got computationally intensive tasks (so-called &lt;i&gt;CPU-bound&lt;/i&gt; tasks) that can be spread across multiple, separated cores. Concurrent programming is better suited for when the task spends a lot of time waiting, such as for a response from a server. These tasks are called &lt;i&gt;IO-bound&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;So asynchronous programming lets us run multiple of these IO-bound computations at the same time on a single thread. They can run at the same time because when they&apos;re waiting for a response, they&apos;re just idle, so we can let the computer keep working on something that isn&apos;t waiting. When we reach a point where we need the result of an asynchronous computation, we must &lt;code&gt;.await&lt;/code&gt; it. In Rust, values that are &apos;awaitable&apos; are known as &apos;futures&apos;.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Rusty weirdness&lt;/h2&gt;&lt;p&gt;&lt;code&gt;async&lt;/code&gt; in Rust may be a bit different from what you&apos;re used to in other languages. Having done asynchronous coding mostly in JavaScript and C#, it certainly was to me. Here&apos;s a few key things to understand:&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;An &lt;code&gt;async&lt;/code&gt; function does not (necessarily) start executing immediately&lt;/h3&gt;&lt;p&gt;To start an asynchronous function, you must either &lt;code&gt;.await&lt;/code&gt; it or launch a task using an &lt;i&gt;executor&lt;/i&gt; (we&apos;ll get to that in a moment). Until this happens, all you have is a &lt;code&gt;Future&lt;/code&gt; that has not started. Let&apos;s look at an example to make it clearer:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;use&lt;/span&gt; async_std::task;
&lt;span class=&quot;hljs-comment&quot;&gt;// ^ we need this for task spawning&lt;/span&gt;

&lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;negate_async&lt;/span&gt;&lt;/span&gt;(n: &lt;span class=&quot;hljs-built_in&quot;&gt;i32&lt;/span&gt;) -&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;i32&lt;/span&gt; {
    &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;Negating {}&quot;&lt;/span&gt;, n);
    task::sleep(std::time::Duration::from_secs(&lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;)).&lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt;;
    &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;Finished sleeping for {}!&quot;&lt;/span&gt;, n);
    n * -&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;
}

&lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;f&lt;/span&gt;&lt;/span&gt;() -&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;i32&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; neg = negate_async(&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;);
    &lt;span class=&quot;hljs-comment&quot;&gt;// ... nothing happens yet&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; neg_task = task::spawn(negate_async(&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;));
    &lt;span class=&quot;hljs-comment&quot;&gt;// ^ this task /is/ started&lt;/span&gt;
    task::sleep(std::time::Duration::from_secs(&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;)).&lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt;;
    &lt;span class=&quot;hljs-comment&quot;&gt;// we sleep for effect.&lt;/span&gt;

    neg.&lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; + neg_task.&lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;// ^ this starts the first task `neg`&lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;// and waits for both tasks to finish&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So in the above little code snippet, here&apos;s what&apos;s going on.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;The first line imports &lt;code&gt;async_std::task&lt;/code&gt;. There&apos;s more on this below, but we need an external library to run futures as the standard library does not come with an &lt;i&gt;executor&lt;/i&gt;.&lt;/li&gt;&lt;li&gt;The async function &lt;code&gt;negate_async&lt;/code&gt; takes as input a signed integer, sleeps for 5 seconds, and returns the negated version of that integer.&lt;/li&gt;&lt;li&gt;The async function &lt;code&gt;f&lt;/code&gt; is more interesting:&lt;/li&gt;&lt;ul&gt;&lt;li&gt;The first line (&lt;code&gt;let neg ...&lt;/code&gt;) creates a &lt;code&gt;Future&lt;/code&gt; of the &lt;code&gt;negate_async&lt;/code&gt; function and assigns it to the &lt;code&gt;neg&lt;/code&gt; variable. &lt;strong&gt;Importantly, it does /not/ start executing yet.&lt;/strong&gt;&lt;/li&gt;&lt;li&gt;The next line of code (&lt;code&gt;let neg_task ...&lt;/code&gt;) uses the &lt;code&gt;task::spawn&lt;/code&gt; function to &lt;strong&gt;start executing&lt;/strong&gt; the &lt;code&gt;Future&lt;/code&gt; returned by &lt;code&gt;negate_async&lt;/code&gt;. Like with &lt;code&gt;neg&lt;/code&gt;, the &lt;code&gt;Future&lt;/code&gt; returned by &lt;code&gt;negate_async&lt;/code&gt; is assigned to the &lt;code&gt;neg_task&lt;/code&gt; variable.&lt;/li&gt;&lt;li&gt;Next: we sleep for a second. This is so that it will be obvious from the output when a task starts running.&lt;/li&gt;&lt;li&gt;Finally, we await both futures, add them together, and return them. By awaiting &lt;code&gt;neg&lt;/code&gt;, we start executing the &lt;code&gt;Future&lt;/code&gt; and run it to completion. Since &lt;code&gt;neg_task&lt;/code&gt; has already been started, we just wait for it to finish.&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;p&gt;So what&apos;s the result of this, then?&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;Negating 2
&lt;span class=&quot;hljs-comment&quot;&gt;# &amp;#x3C;- there&apos;s a 1 second pause here&lt;/span&gt;
Negating 1
Finished sleeping &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; 2!
Finished sleeping &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; 1!&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As we can see, the second future, &lt;code&gt;neg_task&lt;/code&gt;, started executing as soon as it was called---thanks to &lt;code&gt;task::spawn&lt;/code&gt;---while &lt;code&gt;neg&lt;/code&gt; did not start executing until it was awaited.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;You need an external library to use &lt;code&gt;async/.await&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;As was briefly alluded to above, you need to reach for an external library to do asynchronous programming in Rust. This took me a while to understand, as I&apos;m used to it being part of the language experience. In Rust, however, *you need a dedicated &lt;i&gt;executor/*[fn:1]. The executor is what takes care of /executing&lt;/i&gt; the futures, polling them and returning the results when they&apos;re done. The standard library does not come with an executor, so we need to reach out to an external crate for this. There are a few ones to choose from, but the two most prominent ones are &lt;a href=&quot;https://async.rs/&quot;&gt;~async-std~&lt;/a&gt; (which we&apos;re using here) and &lt;a href=&quot;https://tokio.rs/&quot;&gt;~tokio~&lt;/a&gt;.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;A minimal async example!&lt;/h2&gt;&lt;p&gt;Alright, let&apos;s get practical. This is the reason that I&apos;m writing this post. As mentioned at the start, we&apos;ll be creating a super simple application that fetches some Pokémon data and prints it to the console. For preparation, make sure you&apos;ve got at least version 1.39 of Rust and cargo available.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Step 1: creating the application&lt;/h3&gt;&lt;p&gt;Let&apos;s create a new application! Simply run this command in your preferred directory:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;cargo new async-basics&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Step 2: Dependencies&lt;/h3&gt;&lt;p&gt;We&apos;re going to be using &lt;a href=&quot;https://crates.io/crates/async-std&quot;&gt;~async-std~&lt;/a&gt; for spawning tasks, and &lt;a href=&quot;https://crates.io/crates/surf&quot;&gt;~surf~&lt;/a&gt; to fetch data from the API. Let&apos;s add them to the Cargo.toml file. Your whole file should look something like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-toml&quot;&gt;&lt;span class=&quot;hljs-section&quot;&gt;[package]&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;name&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;async-basics&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;version&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;0.1.0&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;authors&lt;/span&gt; = [&lt;span class=&quot;hljs-string&quot;&gt;&quot;Your Name &amp;#x3C;your.email@provider.tld&gt;&quot;&lt;/span&gt;]
&lt;span class=&quot;hljs-attr&quot;&gt;edition&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;2018&quot;&lt;/span&gt;

&lt;span class=&quot;hljs-section&quot;&gt;[dependencies]&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;async-std&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;1&quot;&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;surf&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;1&quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Nice! This is going swimmingly!&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Step 3: Fetch data&lt;/h3&gt;&lt;p&gt;Okay, final step. Let&apos;s modify the &lt;code&gt;main.rs&lt;/code&gt; file. We&apos;ll make it as simple as possible. Here&apos;s what we want to use:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-rust&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;use&lt;/span&gt; async_std::task;
&lt;span class=&quot;hljs-keyword&quot;&gt;use&lt;/span&gt; surf;

&lt;span class=&quot;hljs-comment&quot;&gt;// fetch data from a url and return the results as a string.&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// if an error occurs, return the error.&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;fetch&lt;/span&gt;&lt;/span&gt;(url: &amp;#x26;&lt;span class=&quot;hljs-built_in&quot;&gt;str&lt;/span&gt;) -&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;Result&lt;/span&gt;&amp;#x3C;&lt;span class=&quot;hljs-built_in&quot;&gt;String&lt;/span&gt;, surf::Exception&gt; {
    surf::get(url).recv_string().&lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt;
}

&lt;span class=&quot;hljs-comment&quot;&gt;// execute the fetch function and print the results&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;execute&lt;/span&gt;&lt;/span&gt;() {
    &lt;span class=&quot;hljs-keyword&quot;&gt;match&lt;/span&gt; fetch(&lt;span class=&quot;hljs-string&quot;&gt;&quot;https://pokeapi.co/api/v2/move/surf&quot;&lt;/span&gt;).&lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; {
        &lt;span class=&quot;hljs-literal&quot;&gt;Ok&lt;/span&gt;(s) =&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;Fetched results: {:#?}&quot;&lt;/span&gt;, s),
        &lt;span class=&quot;hljs-literal&quot;&gt;Err&lt;/span&gt;(e) =&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;println!&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&quot;Got an error: {:?}&quot;&lt;/span&gt;, e),
    };
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;/span&gt;() {
    task::block_on(execute());
    &lt;span class=&quot;hljs-comment&quot;&gt;// ^ start the future and wait for it to finish&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That&apos;s all the code you need. In fact, it&apos;s &lt;i&gt;more&lt;/i&gt; than what you need, as some parts have been broken up for legibility. Let&apos;s walk through it!&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;~use~ statements&lt;/dt&gt;&lt;dd&gt;Nothing exciting here. Just importing the crates we declared in the Cargo.toml file: &lt;code&gt;surf&lt;/code&gt; and &lt;code&gt;async_std&lt;/code&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;~fetch~&lt;/dt&gt;&lt;dd&gt;This is simply a thin wrapper around the &lt;code&gt;surf::get&lt;/code&gt; function which returns either the payload as a &lt;code&gt;String&lt;/code&gt; or an &lt;code&gt;Exception&lt;/code&gt; if something went wrong.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;~execute~&lt;/dt&gt;&lt;dd&gt;This function calls fetch with the endpoint for the move &lt;code&gt;Surf&lt;/code&gt;, waits for the result to return, and then matches on the result. If everything went well: print the output. Else: print the error.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;~main~&lt;/dt&gt;&lt;dd&gt;&lt;code&gt;main&lt;/code&gt; simply kicks off &lt;code&gt;execute&lt;/code&gt; and waits for it to finish. &lt;code&gt;task::block_on&lt;/code&gt; is a synchronous counterpart to &lt;code&gt;task::spawn&lt;/code&gt; that starts an asynchronous operation, but blocks until it has finished. Because the &lt;code&gt;main&lt;/code&gt; function can&apos;t itself be &lt;code&gt;async&lt;/code&gt; (at least not at the time of writing), we can&apos;t use &lt;code&gt;.await&lt;/code&gt; in it, but we &lt;i&gt;can&lt;/i&gt; block on asynchronous operations.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Step 4: Extend it!&lt;/h3&gt;&lt;p&gt;Hey, you made it this far; congrats! That&apos;s all I really have in store for you for this one, but if you want to play around a bit more, how about adding &lt;a href=&quot;https://crates.io/crates/serde&quot;&gt;~serde~&lt;/a&gt; and try using &lt;code&gt;surf&lt;/code&gt;&apos;s &lt;code&gt;recv_json&amp;#x3C;T&gt;&lt;/code&gt; instead? If you&apos;d rather keep looking at &lt;code&gt;async/.await&lt;/code&gt;, how about performing multiple requests simultaneously? Or how about making a PokéAPI CLI? (&lt;i&gt;Ooh, that sounds like fun! Hit me up if you&apos;re doing this; I want in!&lt;/i&gt;)&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Parting words and resources&lt;/h2&gt;&lt;p&gt;So there you have it, dear reader. I hope you have found this useful. &lt;code&gt;async/.await&lt;/code&gt; is finally stabilized and it feels like we&apos;ve taken a major leap forward. I&apos;m very much looking forward to seeing what happens in the coming months and what the community makes of this.&lt;/p&gt;&lt;p&gt;If you&apos;re looking for more resources on async Rust, be sure to check out the &lt;a href=&quot;https://rust-lang.github.io/async-book/index.html&quot;&gt;Async Book&lt;/a&gt;. I also recommend the &lt;a href=&quot;https://book.async.rs/&quot;&gt;async-std book&lt;/a&gt; for some extra insights.&lt;/p&gt;&lt;p&gt;Until next time: take care!&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;/div&gt;&lt;dt class=&quot;footnote-label&quot;&gt;[1]&lt;/dt&gt;&lt;dd class=&quot;footnote-content&quot;&gt;&lt;div id=&quot;fn-1&quot; class=&quot;footnote&quot; data-label=&quot;1&quot;&gt;&lt;p&gt;See &lt;a href=&quot;https://www.reddit.com/r/rust/comments/dsy6ax/announcing_rust_1390/f6st41v?utm_source=share&amp;#x26;utm_medium=web2x&quot;&gt;this insightful Reddit comment thread&lt;/a&gt;  for more on this.&lt;/p&gt;&lt;/div&gt;&lt;/dd&gt;</content:encoded></item><item><title><![CDATA[Command Line Control: dirname]]></title><description><![CDATA[In which we have a brief look at dirname, a utility that lets you get the containing directory of any path you send to it. Nothing groundbreaking, but just really nice to have.]]></description><link>https://blog.thomasheartman.com/posts/command-line-control-dirname</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/command-line-control-dirname</guid><pubDate>Mon, 11 Nov 2019 09:36:23 GMT</pubDate><content:encoded>&lt;p&gt;When you need to get the directory name of a file but you only have the full path to the file, what do you do? You could use some fancy parameter expansion, sure, but you might run into some weird edge cases. Personally, I&apos;d suggest just using &lt;code&gt;dirname&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;If you&apos;re familiar with Python and the &lt;code&gt;os&lt;/code&gt; library, the behavior is the same as &lt;code&gt;os.path.dirname&lt;/code&gt;, but even if you&apos;re not, it&apos;s still pretty straightforward. Let&apos;s look at the &lt;code&gt;man&lt;/code&gt; page for the command. It states that given a path, it will output it &quot;with its last non-slash component and trailing slashes removed.&quot; If the path contains no path separators, it will output &lt;code&gt;.&lt;/code&gt;, which is the current directory.&lt;/p&gt;&lt;p&gt;So in a nutshell, that means it will normalize &lt;code&gt;path/to/file.extension&lt;/code&gt; to &lt;code&gt;path/to&lt;/code&gt;, and &lt;code&gt;f.txt&lt;/code&gt; to &lt;code&gt;.&lt;/code&gt;. Because it removes trailing slashes and because it&apos;s not dependent on any file extensions, you can use it repeatedly to move further and further up the tree:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;some/long/path/to/file.extension
-&gt; some/long/path/to
-&gt; some/long/path
-&gt; some/long
-&gt; some
-&gt; .&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So when is this useful? Well, if you&apos;ve got something in your path and you want to find out what else is in that directory, you could do something like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;ls $(dirname $(&lt;span class=&quot;hljs-built_in&quot;&gt;which&lt;/span&gt; &amp;#x3C;cmd&gt;))&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Maybe you want to navigate to that directory or open it in some other command? Yeah, you can do that too.&lt;/p&gt;&lt;p&gt;If you&apos;re still not convinced that you should use &lt;code&gt;dirname&lt;/code&gt;, check out this &lt;a href=&quot;https://unix.stackexchange.com/a/253753&quot;&gt;amazing stack overflow reply&lt;/a&gt; about some of the differences between parameter expansion and &lt;code&gt;dirname&lt;/code&gt;.&lt;/p&gt;</content:encoded></item><item><title><![CDATA[Rust 2020]]></title><description><![CDATA[In which I respond to the recent call for blogs put out by the Rust core team and write down my wishes for Rust in 2020. Yup, GATs and const generics are there, but also slice patterns and a request for better documentation around async development.]]></description><link>https://blog.thomasheartman.com/posts/rust-2020</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/rust-2020</guid><pubDate>Mon, 04 Nov 2019 07:11:56 GMT</pubDate><content:encoded>&lt;p&gt;The end of the year is fast approaching and &lt;i&gt;that&lt;/i&gt;, my friends, means that it&apos;s time for a deluge of end-of-year Rust blogs. The Rust core team has put out a &lt;a href=&quot;https://blog.rust-lang.org/2019/10/29/A-call-for-blogs-2020.html&quot;&gt;call for blogs&lt;/a&gt; to help decide where to take the language next, as they do every year. I&apos;ve been quite invested in Rust for a few years now, so I thought it was about time I joined the fray.&lt;/p&gt;&lt;p&gt;Considering that I spend a disproportionately large amount of time thinking and reading about Rust compared to how much I actually use it, do take my thoughts and wishes here with a grain of salt; they may not be what the community needs the most, it&apos;s just what I&apos;d want in my ideal, little world.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Stabilize slice patterns (&lt;code&gt;#![feature(slice_patterns)]&lt;/code&gt;)&lt;/h2&gt;&lt;p&gt;This is the one language feature I find myself wanting stabilized more than any other. Coming from languages like Haskell---and to a lesser extent Python and JavaScript---that have simple ways to destructure a list of values, doing this can feel quite clunky in Rust. Especially if all you want to do is get the head and the tail of a &lt;code&gt;Vec&lt;/code&gt; or a slice. Yes, the &lt;a href=&quot;https://doc.rust-lang.org/std/primitive.slice.html#method.split_first&quot;&gt;~split first~ function&lt;/a&gt; on &lt;code&gt;slice&lt;/code&gt; does do that, but using it is tricky. In particular, how you handle destructured lists using &lt;code&gt;case of&lt;/code&gt; statements in Haskell feels really ergonomic and intuitive to me.&lt;/p&gt;&lt;p&gt;Luckily, it seems we&apos;re headed in that direction. There is a &lt;a href=&quot;https://github.com/rust-lang/rust/issues/62254&quot;&gt;tracking issue&lt;/a&gt; for the &lt;code&gt;slice_patterns&lt;/code&gt; feature on GitHub, and save for some &lt;a href=&quot;https://github.com/rust-lang/rust/issues/62254#issuecomment-516648011&quot;&gt;remaining compiler&lt;/a&gt; issues, it should be about ready to go in. For now, you can check it out on the nightly channel with the feature toggle &lt;code&gt;#![feature(slice_patterns)]&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;What&apos;s more, because rust matches on slices and not linked lists like in Haskell, we get some extra goodies, such as being able to extract not only the first $n$ items, but also the last $m$ items. &lt;a href=&quot;https://play.rust-lang.org/?version=nightly&amp;#x26;mode=debug&amp;#x26;edition=2018&amp;#x26;gist=bd113b38916127cd8279ec4e7bcbd4fa&quot;&gt;Here&apos;s a little playground link&lt;/a&gt; that I put together demonstrating some cool uses for slice patterns. (Note: you probably &lt;i&gt;can&lt;/i&gt; do this in Haskell somehow---a little bit of searching tells me the &lt;code&gt;ViewPatterns&lt;/code&gt; compiler extension might do the trick---but it&apos;s not baked into the base language like this.)&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Easy async (documentation!)&lt;/h2&gt;&lt;p&gt;I was holding a Rust workshop for some colleagues recently and one of them asked me to create an example of how you&apos;d fetch web data using Rust. I thought this would be a great chance to have a little sneak peek at &lt;code&gt;async/await&lt;/code&gt; before it stabilizes and get familiar with it: I figured I&apos;d try and write a super simple application that fetches some data from an endpoint and dumps it to the terminal. However, I could not make it compile, and if it compiled, it didn&apos;t run properly (presumably because the &lt;code&gt;future&lt;/code&gt; was never started).&lt;/p&gt;&lt;p&gt;What I&apos;d like to see is more information on how to do basic async programming in Rust. &lt;a href=&quot;https://rust-lang.github.io/async-book/01_getting_started/04_async_await_primer.html&quot;&gt;The Async Book&lt;/a&gt; has &lt;a href=&quot;https://rust-lang.github.io/async-book/01_getting_started/04_async_await_primer.html&quot;&gt;a chapter on it&lt;/a&gt;, but I still find it confusing with all the different traits and unstable features. I&apos;ve tried following the example with the Hyper server to make a request, but I keep running into trait bound errors. I&apos;m sure if I sat down and spent some more time on it, it would work, but it feels like it&apos;s missing that &apos;get started in 2 minutes&apos; section.&lt;/p&gt;&lt;p&gt;I&apos;m sure this will improve &lt;i&gt;very&lt;/i&gt; quickly over the next few weeks with the stabilization of &lt;code&gt;async/await&lt;/code&gt;, but for now it&apos;s a hurdle.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Generic Associoted Types (GATs) and const generics&lt;/h2&gt;&lt;p&gt;I&apos;ve lumped these two together because I&apos;ve not really followed either particularly closely, but reading up on them for the purpose of this post, I&apos;m suddenly quite excited by both. In general I&apos;m all for anything that makes the type system more expressive and allows us to create more compile-time constraints.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;GATs ::&lt;/li&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;https://github.com/rust-lang/rust/issues/44265&quot;&gt;Tracking issue&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://github.com/rust-lang/rfcs/blob/master/text/1598-generic_associated_types.md&quot;&gt;Rendered&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;li&gt;Const generics ::&lt;/li&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;https://github.com/rust-lang/rust/issues/44580&quot;&gt;Tracking issue&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://github.com/rust-lang/rfcs/blob/master/text/2000-const-generics.md&quot;&gt;Rendered&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;In summary&lt;/h2&gt;&lt;p&gt;I already had some ideas in mind, so I thought writing this post would be quick and easy, but I ended up diving down multiple rabbit holes, and in the end it took much longer than expected. That said, I learned a lot along the way, and I&apos;m even more excited about the language and where we&apos;re headed now.&lt;/p&gt;&lt;p&gt;Apart from this short wish list, I also think it&apos;s important that we stay aware of the community and keep them in mind. As has been mentioned in a number of other blogs, let&apos;s try and make Rust sustainable for everyone: maintainers, core team, working groups, and community members alike. Let&apos;s also try and move forward with game development, GUI development, and web development. We&apos;re already great. Now let&apos;s be even better. And no matter where we go from here, I&apos;m confident that as long as the community stays warm, welcoming, and inclusive, we&apos;ll have something to be proud of.&lt;/p&gt;&lt;p&gt;Much love ❤️&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Let's read: Haskell Programming from First Principles, pt VI]]></title><description><![CDATA[In which we finally have a closer look at typeclasses and take some time to explore some of the most basic ones, how they work, and how we can use them.]]></description><link>https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-vi</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-vi</guid><pubDate>Mon, 28 Oct 2019 07:24:29 GMT</pubDate><content:encoded>&lt;p&gt;It&apos;s been a while, but welcome back to yet another installment in our read-through of Haskell Programming from First Principles. This time we&apos;re looking at &lt;i&gt;typeclasses&lt;/i&gt;.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;What are typeclasses?&lt;/h2&gt;&lt;p&gt;Typeclasses are like interfaces to your data. The description that I find the most intuitive is that a typeclass is a set of functions that must be implemented for your type to be an &apos;instance&apos; of a typeclass. In classic OO-terms, this is very much like an interface; a contract that you must fulfill to have your type be able to stand in for this interface. In this way, typeclasses are a vehicle for ad-hoc or constrained polymorphism, and let you write code that operates on a more generic set of types than concrete implementations.&lt;/p&gt;&lt;p&gt;Typeclasses allow us to generalize over a set of types and to write functions that can abstract over concrete implementations. For instance: if all a function does with one of its input parameters is test it for equality, then the &lt;code&gt;Eq&lt;/code&gt; typeclass contains all the functionality we need, and we can make that function take any type that implements the &lt;code&gt;Eq&lt;/code&gt; typeclass. Similarly, all numeric literals and their various types implement the typeclass &lt;code&gt;Num&lt;/code&gt;, which defines a set of standard numeric operations, allowing functions to work on any numeric value.&lt;/p&gt;&lt;p&gt;To get a better feel for how this works, let&apos;s look at some of the basic typeclasses and some implementations!&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;&lt;code&gt;Eq&lt;/code&gt;&lt;/h2&gt;&lt;p&gt;&lt;code&gt;Eq&lt;/code&gt;, the typeclass for equality. A very simple typeclass that will let you decide whether two items are the same or not.&lt;/p&gt;&lt;p&gt;The definition is as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Eq&lt;/span&gt; a &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;&lt;/span&gt;
 (==) :: a -&gt; a -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
 (/=) :: a -&gt; a -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Pretty simple, right?  All it needs is a definition for &lt;code&gt;(==)&lt;/code&gt; and one for &lt;code&gt;(/=)&lt;/code&gt;, and even better, the &lt;i&gt;minimal complete definition&lt;/i&gt; --- that is, the least we need to implement to have a complete definition --- is just one of the two functions. The one we don&apos;t define will default to being the negation of the one we do define.&lt;/p&gt;&lt;p&gt;Most data types you&apos;ll work with implement this one already, so you don&apos;t need to worry much about it. Interestingly, because Haskell deals with structural equality, whether a tuple is an instance of &lt;code&gt;Eq&lt;/code&gt; or not, depends on its components. If all the components can be compared for equality, then so can the tuple. This also applies to lists and a range of other data structures.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Writing an instance of the &lt;code&gt;Eq&lt;/code&gt; typeclass&lt;/h3&gt;&lt;p&gt;As an aside, here&apos;s how you&apos;d write your own instance of the &lt;code&gt;Eq&lt;/code&gt; typeclass. It&apos;s a simple instance to write, but that makes it easier to learn from. Let&apos;s look at a basic example using a simple type we define, &lt;code&gt;Bool2&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool2&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;No&lt;/span&gt; | &lt;span class=&quot;hljs-type&quot;&gt;Yes&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;hljs-class&quot;&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;instance&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Eq&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool2&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;&lt;/span&gt;
  &lt;span class=&quot;hljs-type&quot;&gt;Yes&lt;/span&gt; == &lt;span class=&quot;hljs-type&quot;&gt;Yes&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;
  &lt;span class=&quot;hljs-type&quot;&gt;No&lt;/span&gt;  == &lt;span class=&quot;hljs-type&quot;&gt;No&lt;/span&gt;  = &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;
  _   == _   = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So to create an instance, we put &lt;code&gt;instance&lt;/code&gt;, the name of the typeclass, the name of the type to implement it for, and the &lt;code&gt;where&lt;/code&gt; keyword. What follows is an implementation of the functions required for the typeclass. As mentioned above, the &lt;i&gt;minimal complete definition&lt;/i&gt; of the &lt;code&gt;Eq&lt;/code&gt; typeclass only requires one of the functions to be defined, so this is a valid implementation.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;&lt;code&gt;Num&lt;/code&gt;&lt;/h2&gt;&lt;p&gt;The &lt;code&gt;Num&lt;/code&gt; typeclass is one we&apos;ve already looked at quite a bit previously, so we&apos;re not going to dwell on it for too long. It&apos;s a typeclass implemented by most of the numeric types, and the definition is as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Num&lt;/span&gt; a &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;&lt;/span&gt;
  (+) :: a -&gt; a -&gt; a
  (*) :: a -&gt; a -&gt; a
  (-) :: a -&gt; a -&gt; a
  negate :: a -&gt; a
  abs :: a -&gt; a
  signum :: a -&gt; a
  fromInteger :: &lt;span class=&quot;hljs-type&quot;&gt;Integer&lt;/span&gt; -&gt; a&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;&lt;code&gt;Fractional&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;There are various other typeclasses related to &lt;code&gt;Num&lt;/code&gt;, but let&apos;s look at &lt;code&gt;Fractional&lt;/code&gt;, a subtype of &lt;code&gt;Num&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; (&lt;span class=&quot;hljs-type&quot;&gt;Num&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;a&lt;/span&gt;) =&gt; &lt;span class=&quot;hljs-type&quot;&gt;Fractional&lt;/span&gt; a &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;&lt;/span&gt;
  (/) :: a -&gt; a -&gt; a
  recip :: a -&gt; a
  fromRational :: &lt;span class=&quot;hljs-type&quot;&gt;Rational&lt;/span&gt; -&gt; a&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This typeclass requires its type argument, &lt;code&gt;a&lt;/code&gt;, to have an instance of &lt;code&gt;Num&lt;/code&gt;. This means that a &lt;code&gt;Fractional&lt;/code&gt; is a specialized &lt;code&gt;Num&lt;/code&gt; and can be used anywhere a &lt;code&gt;Num&lt;/code&gt; can, but also specifies an extra set of functionality that is not required of  the regular &lt;code&gt;Num&lt;/code&gt; typeclass.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;&lt;code&gt;Ord&lt;/code&gt;&lt;/h2&gt;&lt;p&gt;This typeclass takes care of ordering things, and as such, has a definition concerned with orders and comparisons:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Eq&lt;/span&gt; a =&gt; &lt;span class=&quot;hljs-type&quot;&gt;Ord&lt;/span&gt; a &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;&lt;/span&gt;
  compare :: a -&gt; a -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Ordering&lt;/span&gt;
  (&amp;#x3C;) :: a -&gt; a -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
  (&gt;=) :: a -&gt; a -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
  (&gt;) :: a -&gt; a -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
  (&amp;#x3C;=) :: a -&gt; a -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt;
  max :: a -&gt; a -&gt; a
  min :: a -&gt; a -&gt; a&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note that it has a typeclass constraint of &lt;code&gt;Eq&lt;/code&gt;. If you&apos;re going to be comparing things, you&apos;re going to have to be able to tell whether they are equal or not. These functions all work the way you&apos;d expect them to.&lt;/p&gt;&lt;p&gt;Ord instances (when derived automatically) rely on the way the data type is defined. Looking back on our &lt;code&gt;Bool2&lt;/code&gt; data type from earlier (&lt;code&gt;data Bool2 = No | Yes&lt;/code&gt;), &lt;code&gt;Yes&lt;/code&gt; will be greater than &lt;code&gt;No&lt;/code&gt; because it is defined later. This is similar to how enums work in the C-familiy of languages where they&apos;re usually just fancy names for successive integers starting at an arbitrary point and incrementing by one for each entry. Naturally, if you want to change the ordering, you can, but you&apos;re going to have to implement the typeclass yourself.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;&lt;code&gt;Enum&lt;/code&gt;&lt;/h2&gt;&lt;p&gt;The &lt;code&gt;Enum&lt;/code&gt; typeclass is quite different (yet weirdly similar) to most other things known as enums in other programming languages (at least in my experience). In Haskell, the &lt;code&gt;Enum&lt;/code&gt; typeclass is for types that are &lt;i&gt;enumerable&lt;/i&gt;, that have known &lt;i&gt;predecessors&lt;/i&gt; and &lt;i&gt;successors&lt;/i&gt;. What does this mean? It means you can use instances of this typeclass to generate ranges and lists.&lt;/p&gt;&lt;p&gt;Definition:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Enum&lt;/span&gt; a &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;&lt;/span&gt;
  succ :: a -&gt; a
  pred :: a -&gt; a
  toEnum :: &lt;span class=&quot;hljs-type&quot;&gt;Int&lt;/span&gt; -&gt; a
  fromEnum :: a -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Int&lt;/span&gt;
  enumFrom :: a -&gt; [a]
  enumFromThen :: a -&gt; a -&gt; [a]
  enumFromTo :: a -&gt; a -&gt; [a]
  enumFromThenTo :: a -&gt; a -&gt; a -&gt; [a]&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The most obvious instance of this typeclass would be something like integers, where &lt;code&gt;succ 4&lt;/code&gt; is &lt;code&gt;5&lt;/code&gt; and &lt;code&gt;pred 3&lt;/code&gt; is &lt;code&gt;2&lt;/code&gt;. Similarly, characters can be enumerated just as well, as can ordered data types like &lt;code&gt;Bool&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;Some of the function names listed above are a bit confusing (&lt;code&gt;enumFromThenTo&lt;/code&gt; anyone?), but when you look at it in context it makes more sense. For instance,&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;enumFromThenTo&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;-- yields [1,10,19,28,37,46,55,64,73,82,91,100]&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Where this becomes more interesting is when you see that you can use them in list comprehensions and figure out that there&apos;s alternative ways of using these methods. Here&apos;s the equivalent written as a list comprehension instead:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;[&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;10&lt;/span&gt; .. &lt;span class=&quot;hljs-number&quot;&gt;100&lt;/span&gt;]
&lt;span class=&quot;hljs-comment&quot;&gt;-- yields [1,10,19,28,37,46,55,64,73,82,91,100]&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;&lt;code&gt;Show&lt;/code&gt;&lt;/h2&gt;&lt;p&gt;&lt;code&gt;Show&lt;/code&gt; is a typeclass that provides human-readable string-representations of structured data. GHCi uses this to create &lt;code&gt;String&lt;/code&gt; values that it can print in the terminal. In fact, to have a type be printed in the terminal, it must implement &lt;code&gt;Show&lt;/code&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Show&lt;/span&gt; a &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;&lt;/span&gt;
  showsPrec :: &lt;span class=&quot;hljs-type&quot;&gt;Int&lt;/span&gt; -&gt; a -&gt; &lt;span class=&quot;hljs-type&quot;&gt;ShowS&lt;/span&gt;
  show :: a -&gt; &lt;span class=&quot;hljs-type&quot;&gt;String&lt;/span&gt;
  showList :: [a] -&gt; &lt;span class=&quot;hljs-type&quot;&gt;ShowS&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Unless you&apos;re writing this for your own data structures, you don&apos;t need to worry much about this one. It&apos;s already implemented for all basic types. The minimal complete definition requires either &lt;code&gt;show&lt;/code&gt; or &lt;code&gt;showsPrec&lt;/code&gt;.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Definitions&lt;/h2&gt;&lt;p&gt;We&apos;ve covered a lot of ground here, so let&apos;s take a step back and look at some definitions for this chapter.&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Typeclass inheritance&lt;/dt&gt;&lt;dd&gt;When a typeclass has a &lt;i&gt;superclass&lt;/i&gt;.  This means that only data types that implement the super class can have an instance of the subclass. Going back to the &lt;code&gt;Num&lt;/code&gt; and &lt;code&gt;Fractional&lt;/code&gt; typeclasses: Every &lt;code&gt;Fractional&lt;/code&gt; is also a &lt;code&gt;Num&lt;/code&gt;, but not every &lt;code&gt;Num&lt;/code&gt; is a &lt;code&gt;Fractional&lt;/code&gt;. This makes &lt;code&gt;Num&lt;/code&gt; a superclass of &lt;code&gt;Fractional&lt;/code&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Instance&lt;/dt&gt;&lt;dd&gt;An instance is the definition of how a typeclass should work for a given type. Instances must be unique for a given combination of typeclass and type, i.e. you cannot have two different instances of a typeclass &lt;code&gt;T&lt;/code&gt; for a single type &lt;code&gt;a&lt;/code&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Derived instances&lt;/dt&gt;&lt;dd&gt;Some typeclasses are so obvious or common that they can be automatically implemented for a data type. Automatically deriving typeclasses like this is done by specifying it after the data declaration: &lt;code&gt;data MyType = A | B deriving (Eq, Show)&lt;/code&gt;&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Command Line Control: vipe]]></title><description><![CDATA[In which we discover a new command line tool, Vipe, and look at how we can use it to easily modify and apply Kubernetes objects across namespaces.]]></description><link>https://blog.thomasheartman.com/posts/command-line-control-vipe</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/command-line-control-vipe</guid><pubDate>Mon, 21 Oct 2019 21:11:58 GMT</pubDate><content:encoded>&lt;p&gt;Every now and then you come across a little tool that makes you go &quot;/Oooh, that&apos;s neat. Wish I&apos;d known about that before./&quot; &lt;code&gt;vipe&lt;/code&gt; is one of those. Granted, you might not need it every day, but sometimes it&apos;s just the right tool for the job.&lt;/p&gt;&lt;p&gt;The tl;dr: is that it&apos;s a way for you to pipe something into your &lt;code&gt;$EDITOR&lt;/code&gt; and then pipe it on into another command when you&apos;re done editing it. That&apos;s right! There&apos;s no need to save it to an intermediate file and clutter your workspace, nor do you have to do everything via &lt;code&gt;sed&lt;/code&gt; (though that can be a fun experience).&lt;/p&gt;&lt;p&gt;How did this come about? Well, we wanted to migrate a config map from one OpenShift project to another at work. Rather than saving the config to an intermediate file, we wanted to see if we could pipe it through an editor and back into &lt;code&gt;oc apply&lt;/code&gt; with the required changes. And sure enough, we could:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# kubectl should work just the same as oc&lt;/span&gt;
oc get configmap &amp;#x3C;config-map&gt; -o yaml \
| vipe | oc apply -f -&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The first command gets the config map from the server in yaml format, the second (&lt;code&gt;vipe&lt;/code&gt;!) pipes it into your &lt;code&gt;$EDITOR&lt;/code&gt;, letting you make any necessary changes, and the last one takes your updated config map, applying it to the server for you.&lt;/p&gt;&lt;p&gt;&lt;code&gt;vipe&lt;/code&gt; is available as part of the &lt;code&gt;moreutils&lt;/code&gt; package, available via various package managers including Apt, Nix, and Homebrew. There&apos;s a couple more interesting packages in there too, so it&apos;s worth checking it out just for that!&lt;/p&gt;</content:encoded></item><item><title><![CDATA[On differentiation]]></title><description><![CDATA[In which I talk about differentiation, clarifying some issues I've had with reading the course material for where I study and giving some examples of how I think it should be presented.]]></description><link>https://blog.thomasheartman.com/posts/on-differentiation</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/on-differentiation</guid><pubDate>Mon, 14 Oct 2019 06:54:56 GMT</pubDate><content:encoded>&lt;p&gt;Let&apos;s talk math. Specifically, calculating derivatives through differentiation. I&apos;ve been taking a calculus course at my local university lately, and one of the things that&apos;s come up and bit me a couple times is how a lot of the reference material we&apos;re given for differentiation shows off differentiation in a way that isn&apos;t entirely clear. So in this post I want to record for the future me just how differentiation works.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Implicit derivatives&lt;/h2&gt;&lt;p&gt;When the common derivatives are listed, they&apos;re listed for the variable $x$, and the fact that you&apos;ll need to apply the chain rule ($(f \circ g)&apos; = (f &apos; \circ g)g&apos;$ or $(f(g(x)))&apos; = f&apos;(g(x)g&apos;(x)$) when working with expressions is not really made clear. For instance, let&apos;s look at the derivative for natural logarithms: $$ (\ln |x|)&apos; = \frac{1}{x} $$&lt;/p&gt;&lt;p&gt;This works great for a single variable $x$, because the derivative of $x$ is $1$. However, in cases where $x$ is an expression ($2x$, $x^2$, $\sin x$, ...), you&apos;ll need to multiply that fraction with the derivative of the expression $x$. For this reason, I think it&apos;d be much clearer if the formula sheet had it listed like this: $$ (ln |x|)&apos; = \frac{x&apos;}{x} $$&lt;/p&gt;&lt;p&gt;Similarly, this also goes for other derivatives, like sines, cosines, powers of $e$, and so on:&lt;/p&gt;&lt;p&gt;$$(\arcsin x)&apos; = \frac{x&apos;}{\sqrt{1 - x^2}}$$&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Add updated files only]]></title><description><![CDATA[In which we look at the much-overlooked option for git add: --update. This option lets you add any and all files as long as they are currently tracked by git, but will ignore any files that git isn't tracking.]]></description><link>https://blog.thomasheartman.com/posts/add-updated-files-only</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/add-updated-files-only</guid><pubDate>Mon, 07 Oct 2019 20:49:51 GMT</pubDate><content:encoded>&lt;p&gt;Sometimes you&apos;re just a hair too quick when working with git, run a little &lt;code&gt;git add -A&lt;/code&gt;  or &lt;code&gt;git add .&lt;/code&gt;, and then let an unwanted file or two come along for the ride. Regardless of whether it&apos;s just random scribbles or actual secrets, it&apos;s pretty annoying. And if no-one notices before you push it to the remote (or open a merge request), it could be a good few levels worse. Today I learned a way to avoid this, and I want to share it with you, dear reader.&lt;/p&gt;&lt;p&gt;Now, just to be clear: I don&apos;t actually recommend you blindly add all files in a directory or project to git. It&apos;s usually better to be explicit about what you&apos;re adding. Sometimes, though, it&apos;s just easier to add everything. Claiming that I&apos;ve never done it or that it&apos;s never caused me grief would be disingenuous at best.&lt;/p&gt;&lt;p&gt;So what&apos;s the solution you ask? It&apos;s a simple flag you can pass to &lt;code&gt;git add&lt;/code&gt;: &lt;code&gt;-u&lt;/code&gt; or &lt;code&gt;--update&lt;/code&gt;. Much like the flag name would suggest, this makes it add only updated files.&lt;/p&gt;&lt;p&gt;The &lt;a href=&quot;https://git-scm.com/docs/git-add&quot;&gt;docs&lt;/a&gt; say that this option will &quot;/update the index just where it already has an entry matching &amp;#x3C;pathspec&gt;. This &lt;strong&gt;removes as well as modifies index entries&lt;/strong&gt; to match the working tree, *but adds no new files*/&quot;. So you can point it to a directory and it will add all changed or deleted files in that directory, but no new files.&lt;/p&gt;&lt;p&gt;You can also use it &lt;strong&gt;without a path&lt;/strong&gt;, which will just add all deleted and modified files: &quot;/If no &amp;#x3C;pathspec&gt; is given when -u option is used, *all tracked files in the entire working tree are updated*/&quot;.&lt;/p&gt;&lt;p&gt;So next time you want to blindly add all your changes (but no new files!) to git:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git add -u&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Psst! Here&apos;s a little bonus resource for ya: For more information on the behavior of &lt;code&gt;git add&lt;/code&gt; with different options, check the answers to this &lt;a href=&quot;https://stackoverflow.com/questions/572549/difference-between-git-add-a-and-git-add&quot;&gt;stack overflow question&lt;/a&gt;, which is what put me on the trail of &lt;code&gt;git add -u&lt;/code&gt; in the first place.&lt;/p&gt;</content:encoded></item><item><title><![CDATA[A mentor's thoughts]]></title><description><![CDATA[In which I discuss my experiences as a mentor at Oslo Legal Hackathon 2019, what I learned about myself, and why I think it's something you should try.]]></description><link>https://blog.thomasheartman.com/posts/a-mentors-thoughts</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/a-mentors-thoughts</guid><pubDate>Mon, 30 Sep 2019 06:52:57 GMT</pubDate><content:encoded>&lt;p&gt;I was a mentor at &lt;a href=&quot;https://www.legalhackathon.no/&quot;&gt;Oslo Legal Hackathon&lt;/a&gt; this past weekend, and while I&apos;ve been to hackathons before, this was my first time participating as a mentor. I wasn&apos;t quite sure what to expect, but I felt ready.&lt;/p&gt;&lt;p&gt;And indeed, everything went pretty swimmingly. Well, mostly. There was a shortage of tech people, and I ended up co-mentoring a team consisting solely of people from the legal industry. Not ideal at an event that&apos;s supposed to bring legal and tech together, but they made it to the final round by focusing on the things that they could do rather than what they couldn&apos;t. But even though I think my team did a terrific job, that&apos;s not really what I want to focus on. Rather, I want to talk about the act of mentoring and how it feels different from participating.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Stepping down&lt;/h2&gt;&lt;p&gt;Admittedly, I like being in charge. I like overseeing what&apos;s going on and giving my input on it. I often end up as team lead or in similar positions. Being a mentor is different.&lt;/p&gt;&lt;p&gt;&lt;i&gt;Yes&lt;/i&gt;, I could still get an overview of where the team was headed, and &lt;i&gt;yes&lt;/i&gt;, I could still give my input on it, but in the end, I knew that I had no real say in the matter.&lt;/p&gt;&lt;p&gt;I&apos;m also very competitive. It&apos;s probably one of the main reasons that I work as hard as I do. Sure, I enjoy what I do, but I also want to be the very best. &lt;strong&gt;Like no one ever was&lt;/strong&gt;.&lt;/p&gt;&lt;p&gt;By being slightly divorced from the process and by not actually being on the team, I could take a step back, breathe, and just enjoy seeing them work and the solutions they came up with.&lt;/p&gt;&lt;p&gt;In fact, I think &lt;i&gt;that&lt;/i&gt; might be the most important thing I learned about myself: I enjoy &lt;strong&gt;enabling&lt;/strong&gt; a team and seeing them succeed at least as much as I enjoy being on the team. They&apos;re two very different, yet very similar experiences.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;For future reference&lt;/h2&gt;&lt;p&gt;To close this all out, then: would I do it again? Yes. No doubt. Not only was it great fun, it was also a fantastic chance to grow my network, both within tech and within the legal industry, and to get to better know my coworkers and fellow mentors.&lt;/p&gt;&lt;p&gt;I&apos;ve been trying to come up with some cons, but I haven&apos;t really been able to; the event was well organized, the participants and organizers were all nice people, there was food and drinks, and it was just a fun event all around.&lt;/p&gt;&lt;p&gt;A bit tongue-in-cheek, perhaps, but it felt great being able to come in, give feedback, express some opinions, and then go away and have someone else do the dirty work for you. I think I understand why people want to be managers now.&lt;/p&gt;&lt;p&gt;And finally, even if I&apos;ve only been at this for a comparatively small amount of time, I felt that I really had something to contribute to the team, that I could make a difference, that I could add value. So remember: Even if you&apos;re not the most decorated or recognized individual, don&apos;t sell yourself short! As long as you invest your time and are genuinely passionate about what you do, you&apos;ll be a valuable asset to &lt;i&gt;any&lt;/i&gt; team, no matter the role.&lt;/p&gt;&lt;p&gt;So don&apos;t quit, don&apos;t stop exploring new things, and don&apos;t stop making yourself uncomfortable. If you&apos;re curious, go for it!&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Amending authors]]></title><description><![CDATA[In which we look at amending git commit authors, both the steps you need to take to change the last few commits (or all of them), and how we can create a one-liner that just magically takes care of it for us.]]></description><link>https://blog.thomasheartman.com/posts/amending-authors</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/amending-authors</guid><pubDate>Mon, 23 Sep 2019 07:02:37 GMT</pubDate><content:encoded>&lt;p&gt;If you juggle multiple git user names or emails in your job and/or spare time, it&apos;s not unlikely that you&apos;ll end up committing code with the wrong user. At a glance, there&apos;s no easy way to fix this; you can&apos;t just change the author of a commit---they&apos;re immutable, after all---but you &lt;i&gt;can&lt;/i&gt; delete a commit and create a new one. This sounds tedious, and doing it manually &lt;i&gt;is&lt;/i&gt; tedious, but fear not, for I am here to show you how we can do it automatically!&lt;/p&gt;&lt;p&gt;The trick is based on the answers to &lt;a href=&quot;https://stackoverflow.com/questions/3042437/how-to-change-the-commit-author-for-one-specific-commit&quot;&gt;this Stack Overflow question&lt;/a&gt;. In short, it&apos;s just a matter of rebasing off a specific commit and then automating the process of accepting the commit as-is while changing the author.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The basics: &lt;code&gt;git rebase -i&lt;/code&gt;&lt;/h2&gt;&lt;p&gt;Interactively rebasing lets you choose a commit to rebase off and then choose what you want to do with all the commits since (edit, pick, delete, etc.). In this case, we want to amend the commits, so change them all to &lt;code&gt;edit&lt;/code&gt;. If you want to leave some commits untouched, just mark them as &lt;code&gt;pick&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;When rebasing interactively, git will stop after each commit we&apos;ve chosen to edit, saying you can amend the commit by running &lt;code&gt;git commit --amend&lt;/code&gt;. We want to reuse the same commit message, but edit the author, and the trick for that is using the &lt;code&gt;--reset-author&lt;/code&gt; and &lt;code&gt;--no-edit&lt;/code&gt; options.&lt;/p&gt;&lt;p&gt;So far, our process looks like this:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Set the right user details in our config.&lt;/li&gt;&lt;/ol&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git config user.name &amp;#x3C;correct user name&gt;
git config user.email &amp;#x3C;correct user name&gt;&lt;/code&gt;&lt;/pre&gt;&lt;ol&gt;&lt;li&gt;Initiate the rebase.&lt;/li&gt;&lt;/ol&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git rebase -i &amp;#x3C;commit &lt;span class=&quot;hljs-built_in&quot;&gt;hash&lt;/span&gt;&gt;&lt;/code&gt;&lt;/pre&gt;&lt;ol&gt;&lt;li&gt;Change the commit&apos;s author and continue the rebase.&lt;/li&gt;&lt;/ol&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# amend the commit, changing the author, but leaving the message intact.&lt;/span&gt;
git commit --amend --reset-author --no-edit

git rebase --&lt;span class=&quot;hljs-built_in&quot;&gt;continue&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;ol&gt;&lt;li&gt;Repeat step 3 until you&apos;re done&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;Tedious, but at least it works. Most likely, this doesn&apos;t happen often enough that you&apos;ll need to automate it, so we could just leave it, but where&apos;s the fun in that?&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Taking it further&lt;/h2&gt;&lt;p&gt;Let&apos;s think about what we want to do: For each commit since a specific one, we want to change the author and continue the rebase. Sounds pretty easy, right? We&apos;ll just need to figure out how many iterations we need, and we have ourselves a one-liner!&lt;/p&gt;&lt;p&gt;So how do we go about finding out how many commits we need to change? We could count, but git does offer a command we can use for it: &lt;code&gt;git rev-list&lt;/code&gt;. It doesn&apos;t do much without any arguments, but with the &lt;code&gt;--count&lt;/code&gt; flag and a commit, we can start working some magic. The &lt;code&gt;--count&lt;/code&gt; functionality, as you might expect, counts the number of commits up until the provided hash by default, but, conveniently, it can also operate on commit ranges! (As an aside: &lt;code&gt;git rev-list&lt;/code&gt; has a lot of interesting uses, so go &lt;a href=&quot;https://git-scm.com/docs/git-rev-list&quot;&gt;read the docs&lt;/a&gt; if you want to know more!)&lt;/p&gt;&lt;p&gt;To get the number of commits since the one we&apos;re using as the rebase root (thus &lt;i&gt;not&lt;/i&gt; changing):&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git rev-list &amp;#x3C;rebase root &lt;span class=&quot;hljs-built_in&quot;&gt;hash&lt;/span&gt;&gt;...HEAD&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This is starting to look pretty good. If we put something together, it might look something like this, with &lt;code&gt;&amp;#x3C;root&gt;&lt;/code&gt; being the hash of the commit we want to rebase off:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;n=$(git rev-list --count &amp;#x3C;root&gt;...HEAD);\
git rebase -i &amp;#x3C;root&gt;;\
&lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; $(seq &lt;span class=&quot;hljs-variable&quot;&gt;$n&lt;/span&gt;);\
&lt;span class=&quot;hljs-keyword&quot;&gt;do&lt;/span&gt;\
  git commit --amend --reset-author --no-edit;\
  git rebase --&lt;span class=&quot;hljs-built_in&quot;&gt;continue&lt;/span&gt;;\
&lt;span class=&quot;hljs-keyword&quot;&gt;done&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;or in Fish for all you cool kids:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;set&lt;/span&gt; n (git rev-list --count &amp;#x3C;root&gt;...HEAD);\
git rebase -i &amp;#x3C;root&gt;;\
&lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; (seq &lt;span class=&quot;hljs-variable&quot;&gt;$n&lt;/span&gt;);\
  git commit --amend --reset-author --no-edit;\
  git rebase --&lt;span class=&quot;hljs-built_in&quot;&gt;continue&lt;/span&gt;;\
end&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note that this is a pretty naive way to do it. As outlined in &lt;a href=&quot;https://stackoverflow.com/questions/31997999/number-of-commits-between-two-commitishes&quot;&gt;this Stack Overflow question&lt;/a&gt;, the number of commits you&apos;re looking at might not be what&apos;s returned by &lt;code&gt;git rev-list&lt;/code&gt; directly. For instance, if you have multiple branches that have been merged in, you might need to add the &lt;code&gt;--first-parent&lt;/code&gt; flag to get the desired behavior.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Special case: what about rebasing off the root of the repo?&lt;/h2&gt;&lt;p&gt;Ah, yes; this is what I&apos;ve actually had to do each time I&apos;ve been amending authors. We&apos;ve tackled rebasing off a repo root in a &lt;a href=&quot;https://blog.thomasheartman.com/posts/rebasing-off-a-repo-root/&quot;&gt;prior post&lt;/a&gt;, so we already know that we can pass the &lt;code&gt;--root&lt;/code&gt; flag to &lt;code&gt;git rebase&lt;/code&gt;. When we rebase off the root, we don&apos;t need to deal with commit hashes, so it actually becomes a bit simpler:&lt;/p&gt;&lt;p&gt;In bash:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;n=$(git rev-list --count HEAD);\
git rebase -i --root;\
&lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; $(seq &lt;span class=&quot;hljs-variable&quot;&gt;$n&lt;/span&gt;);
&lt;span class=&quot;hljs-keyword&quot;&gt;do&lt;/span&gt;\
  git commit --amend --reset-author --no-edit;\
  git rebase --&lt;span class=&quot;hljs-built_in&quot;&gt;continue&lt;/span&gt;;\
&lt;span class=&quot;hljs-keyword&quot;&gt;done&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And in fish:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;set&lt;/span&gt; n (git rev-list --count HEAD);\
git rebase -i --root;\
&lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; (seq &lt;span class=&quot;hljs-variable&quot;&gt;$n&lt;/span&gt;);\
  git commit --amend --reset-author --no-edit;\
  git rebase --&lt;span class=&quot;hljs-built_in&quot;&gt;continue&lt;/span&gt;;\
end&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Git config management]]></title><description><![CDATA[In which we dive into git config management with a short overview of the format, and of where git searches for config files by default. We look at how to set values, unsetting them, inspecting them, and how to list all your config values. Plus: a neat trick to debug config collisions!]]></description><link>https://blog.thomasheartman.com/posts/git-config-management</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/git-config-management</guid><pubDate>Mon, 16 Sep 2019 07:00:10 GMT</pubDate><content:encoded>&lt;p&gt;We&apos;ve been looking a lot at how to tweak git to your liking, which is usually done through your git config file. Sometimes, though, you&apos;ll find that the configuration isn&apos;t working as you wanted, so I thought it&apos;d be a good idea to look at how you can inspect, unset, and list configuration values from the command line.&lt;/p&gt;&lt;p&gt;Before we dive in, let&apos;s have a few words about how your git config files work. Your config files use a specific format which, according to the &lt;a href=&quot;https://git-scm.com/docs/git-config#_configuration_file&quot;&gt;docs&lt;/a&gt;, &quot;consists of sections and variables. A section begins with the name of the section in square brackets and continues until the next section begins.&quot; That&apos;s enough for what we need right now, but go read up if you&apos;re interested.&lt;/p&gt;&lt;p&gt;Furthermore, git config files &apos;cascade&apos;, and git, by default, searches four locations on your system, where later entries override earlier ones:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;~/etc/gitconfig~&lt;/dt&gt;&lt;dd&gt;The system wide config&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;~$XDG_CONFIG_HOME/git/config~&lt;/dt&gt;&lt;dd&gt;Falls back to &lt;code&gt;$HOME/.config/git/config&lt;/code&gt; if &lt;code&gt;$XDG_CONFIG_HOME&lt;/code&gt; is not set or empty.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;~~/.gitconfig~&lt;/dt&gt;&lt;dd&gt;Your user-specific, &apos;global&apos; config file&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;~$GIT_DIR/config~&lt;/dt&gt;&lt;dd&gt;Repo-specific config file&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;Again, see &lt;a href=&quot;https://git-scm.com/docs/git-config#FILES&quot;&gt;the specific section of the documentation&lt;/a&gt; for more information.&lt;/p&gt;&lt;p&gt;One last thing: All setting and unsetting of values apply only to your user configurations, and they are local---repo-specific---by default. To make them apply to your global config, pass the &lt;code&gt;--global&lt;/code&gt; flag.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Setting values&lt;/h2&gt;&lt;p&gt;To set a value, simply run a command on the form&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# default (local)&lt;/span&gt;
git config &amp;#x3C;section&gt;.&amp;#x3C;key&gt; &amp;#x3C;value&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# global&lt;/span&gt;
git config --global &amp;#x3C;section&gt;.&amp;#x3C;key&gt; &amp;#x3C;value&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;For instance, to change the value of the &lt;code&gt;commentChar&lt;/code&gt; entry of the &lt;code&gt;core&lt;/code&gt; section to &lt;code&gt;;&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git config core.commentChar &lt;span class=&quot;hljs-string&quot;&gt;&apos;;&apos;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Unsetting values&lt;/h2&gt;&lt;p&gt;Similarly, if you want to unset a value, use the &lt;code&gt;--unset&lt;/code&gt; flag:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git config --&lt;span class=&quot;hljs-built_in&quot;&gt;unset&lt;/span&gt; &amp;#x3C;section&gt;.&amp;#x3C;key&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So if you have overridden the &lt;code&gt;core.commentChar&lt;/code&gt; value, this is the command to undo that and reset it to the default value, &lt;code&gt;#&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git config --&lt;span class=&quot;hljs-built_in&quot;&gt;unset&lt;/span&gt; core.commentChar&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Inspecting config values&lt;/h2&gt;&lt;p&gt;Sometimes, you want to know what a value has been set to. For this, pass the &lt;code&gt;--get&lt;/code&gt; flag and the section and key of the value you want to look up:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git config --get &amp;#x3C;section&gt;.&amp;#x3C;key&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So if you&apos;re wondering what your user&apos;s name is, for instance:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git config --get user.name&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;A few things to note about getting the values&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Git will show you the last value it finds in the chain&lt;/dt&gt;&lt;dd&gt;So if you set your username in your global config, but set a different one in a repo and invoke this command from the repo, it would show you only the repo-specific one.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;The output will be empty if you have not explicitly set the value&lt;/dt&gt;&lt;dd&gt;In other words, if it&apos;s not in your config files, git won&apos;t show it to you. So if you&apos;re looking to inspect git&apos;s default values, that&apos;s not going to work.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Finding the config value sources&lt;/h2&gt;&lt;p&gt;Sometimes you just want to inspect what values you&apos;re setting in your config. You can do this by passing the &lt;code&gt;--list&lt;/code&gt; flag:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git config --list&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;By default, this will just throw all your configuration at you, which isn&apos;t all that helpful. However, it takes a pretty handy flag, &lt;code&gt;--show-origin&lt;/code&gt;, which lists your configuration in two columns, with the first one being the file in which it was set and the second being the the key-value pairs.&lt;/p&gt;&lt;p&gt;If you ever find that some value isn&apos;t taking effect the way you expect, this is a great way to check what values are getting set in what locations:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git config --list --show-origin&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;For instance, if you&apos;ve changed your global user name, but it&apos;s not taking effect in the current repo, you could pipe it into &lt;code&gt;grep&lt;/code&gt; and look for duplicates:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git config --list --show-origin | grep &lt;span class=&quot;hljs-string&quot;&gt;&quot;user.name=&quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Commit message templates]]></title><description><![CDATA[In which we take a closer look at using commit message templates to increase our productivity by decreasing the mental overhead required to write a message. We look at how to set up templates, how to unset them, and a couple of ideas on what to put in them.]]></description><link>https://blog.thomasheartman.com/posts/commit-message-templates</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/commit-message-templates</guid><pubDate>Mon, 09 Sep 2019 03:53:29 GMT</pubDate><content:encoded>&lt;p&gt;Here&apos;s a statement for ya: if you&apos;re working on a project with someone else, you &lt;i&gt;should&lt;/i&gt; be using a commit message template. Not only will it help increase the consistency and usefulness of your messages, but also, and perhaps more importantly, it will reduce the cognitive load required to write a message and the time it takes to write it. I can only speak for myself, but I know that having to go look up information about how a commit message should be structured and what it references causes some much unneeded context switching, resulting in a less efficient workflow.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Setup&lt;/h2&gt;&lt;p&gt;Setting up commit message templates requires only a few steps:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Create a template.&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;You can use any text file as a template; just put what you want to show up in the commit message buffer in there. Plain lines of text will show up as content, while lines starting with the comment character (&lt;code&gt;#&lt;/code&gt; by default) show up as comments.&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Add it to the git config as a commit template.&lt;/li&gt;&lt;/ol&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git config commit.template &amp;#x3C;path/to/file&gt;&lt;/code&gt;&lt;/pre&gt;&lt;ol&gt;&lt;li&gt;Done! Now try committing something.&lt;/li&gt;&lt;/ol&gt;&lt;hr&gt;&lt;p&gt;When doing this, you&apos;re assigning the template locally (to the current repo). If you&apos;d rather do it globally, pass the &lt;code&gt;--global&lt;/code&gt; option.&lt;/p&gt;&lt;p&gt;If you want to share the template across multiple projects in a certain subdirectory, you can do that by combining the template with git&apos;s functionality for conditional includes. Be aware, however, that given a relative path to a file, git will look for the file relative to the including configuration&apos;s location. While this can potentially be exploited to use different templates for different projects, I&apos;ve not found the need for it thus far, and have stuck with a single template with an absolute path.&lt;/p&gt;&lt;p&gt;If you want to unset the template, use the &lt;code&gt;git config --unset&lt;/code&gt; functionality:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git config --&lt;span class=&quot;hljs-built_in&quot;&gt;unset&lt;/span&gt; commit.template&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Commit template ideas&lt;/h2&gt;&lt;p&gt;Different teams and projects have different needs when it comes to commit messages, so there&apos;s no &apos;one size fits all&apos;, but here&apos;s a few ideas based on message formats in teams I&apos;ve been a part of.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Label listing&lt;/h3&gt;&lt;p&gt;If you label your commits with the type of work they contain to and have a defined set of labels (e.g. &apos;feature&apos;, &apos;bug&apos;, &apos;chore&apos;, &apos;refactor&apos;, etc.), it might be a good idea to list all the different options in the template, so that you can look through them whenever you&apos;re committing some code. List them using commented lines and you don&apos;t even have to delete them; they&apos;ll just show up as extra info in the commit buffer.&lt;/p&gt;&lt;p&gt;While experienced members of the team are likely to know these by heart, it&apos;s very helpful for a new person to have the list right there in the commit buffer so that they don&apos;t have to go look them up.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Issue identification&lt;/h3&gt;&lt;p&gt;If the standard says to have an issue/ticket ID listed in the commit message, you could put a little placeholder in the template that tells you to replace it with the relevant ID.&lt;/p&gt;&lt;p&gt;If you also work with feature branches and name them according to the feature/issue ID that they correspond to, you could even have git fill in this issue number automatically by using hooks, as explained in my previous post. I have found this to save me a surprisingly large amount of time and mental overhead.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Very specific formats&lt;/h3&gt;&lt;p&gt;For when your message needs to match a very specific format and it&apos;s hard to remember exactly what goes where, templates are a perfect solution.&lt;/p&gt;&lt;p&gt;For instance, if you&apos;re working with a combination of the above two, where you want both the label &lt;i&gt;and&lt;/i&gt; the ID, and you want them in a specific order, maybe even with a specific separator (&lt;i&gt;seems like a hassle, but just roll with it&lt;/i&gt;), you could create a template that you could just fill in with the relevant parts, saving you having to look up what the format is every time.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Rebasing off a repo root]]></title><description><![CDATA[In which we have the briefest of looks at how you can rebase off the root of a git repository, allowing us to pick, squash, and reword each and every commit in the repository's entire history.]]></description><link>https://blog.thomasheartman.com/posts/rebasing-off-a-repo-root</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/rebasing-off-a-repo-root</guid><pubDate>Mon, 02 Sep 2019 07:52:55 GMT</pubDate><content:encoded>&lt;p&gt;Ever had to change something about all the commits in a git repo before pushing it to a remote? As in from the &lt;i&gt;very first&lt;/i&gt; commit in a repo? Maybe you&apos;ve started a repo locally and when you&apos;re ready to push it, you realize that you&apos;ve used the wrong author or messed up the format of the commit messages; or maybe you just want to squash those first few commits into a single concise package.&lt;/p&gt;&lt;p&gt;In these situations, my first response is to do to an interactive rebase (&lt;code&gt;git rebase -i&lt;/code&gt;). Usually when I&apos;m rebasing, though, I&apos;m in a project that has an upstream and where I&apos;m rebasing off a specific commit or branch. For situations where you don&apos;t have a commit to rebase off, but you want to rebase the &lt;i&gt;entire&lt;/i&gt; history or at least the &lt;i&gt;very first&lt;/i&gt; commit: What do you do?&lt;/p&gt;&lt;p&gt;The answer, my friend, is that you pass the &lt;code&gt;--root&lt;/code&gt; option:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git rebase -i --root&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That&apos;ll let you pick, reword, edit, squash, fixup, exec, drop, label, reset, or merge &lt;i&gt;all&lt;/i&gt; of your commits from the &apos;dawn of time.&apos;&lt;/p&gt;&lt;p&gt;Have fun!&lt;/p&gt;</content:encoded></item><item><title><![CDATA[Automate your commit messages]]></title><description><![CDATA[In which we look at how we can use git hooks to automatically fill in certain bits of the commit message for use based on the state of the repository and our current branch. Also: A tiny look at differences between BSD and GNU sed.]]></description><link>https://blog.thomasheartman.com/posts/automate-your-commit-messages</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/automate-your-commit-messages</guid><pubDate>Mon, 26 Aug 2019 07:48:50 GMT</pubDate><content:encoded>&lt;p&gt;Git has a lot of inbuilt functionality that you might not use all the time, but which is oh-so-handy when you need it. One such thing is &lt;i&gt;hooks&lt;/i&gt;. These can be used to do stuff like formatting your code before committing or running tests before pushing to the remote. Today, though, let&apos;s look at how we can use it to automatically fill in part of your commit messsage.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;How did this come up?&lt;/h2&gt;&lt;p&gt;The team I&apos;m on at work uses a system for commit messages and branch names where they should both start with the issue id of whatever task we&apos;re working on. Using GitLab, they end up looking something like &lt;code&gt;#2 Adds sorting functionality to UI&lt;/code&gt; (&lt;i&gt;we can argue about commit message tenses later&lt;/i&gt;) and &lt;code&gt;#42/new-sorting-algorithm&lt;/code&gt;, respectively.&lt;/p&gt;&lt;p&gt;If you&apos;re like me, your mind should be poking you right about now, saying that that&apos;s a lot of duplication; surely we don&apos;t need all of that? Well, you could argue that with feature branches scoped to issues and no fast-forward merges, the branch name should be enough, but it doesn&apos;t really show up in condensed commit logs etc., so it&apos;s nice to have the issue number available for when you need it.&lt;/p&gt;&lt;p&gt;But not to worry; we can make the computer fill it in for us!&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Picking the right hook&lt;/h2&gt;&lt;p&gt;Git has quite a few hooks available; if you check the &lt;code&gt;.git/hooks&lt;/code&gt; directory of a tracked project, you should find a bunch of files named &lt;code&gt;&amp;#x3C;hook name&gt;.sample&lt;/code&gt;. Most of the hook names are fairly descriptive, but you could always &lt;a href=&quot;https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks&quot;&gt;look them up&lt;/a&gt; if you want to know more.&lt;/p&gt;&lt;p&gt;In our case we&apos;re interested in hooking into the system right before the commit message buffer appears on our screen, so we&apos;re going to go with the &lt;code&gt;prepare-commit-msg&lt;/code&gt; hook.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Auto-filling the message&lt;/h2&gt;&lt;p&gt;Now, my team has a template we use for commits, which starts with &lt;code&gt;#[task number]&lt;/code&gt;. Using this knowledge, we can do some fancy shell magic and replace it with the task from the branch name.&lt;/p&gt;&lt;p&gt;The whole script looks like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;&lt;span class=&quot;hljs-meta&quot;&gt;#!/bin/sh&lt;/span&gt;

TASK_NO=$(git rev-parse --abbrev-ref HEAD | cut -d &lt;span class=&quot;hljs-string&quot;&gt;&apos;/&apos;&lt;/span&gt; -f 1)
&lt;span class=&quot;hljs-comment&quot;&gt;# BSD sed (macOS)&lt;/span&gt;
sed -i&lt;span class=&quot;hljs-string&quot;&gt;&apos;&apos;&lt;/span&gt; -e &lt;span class=&quot;hljs-string&quot;&gt;&quot;s/#\[task number\]/&lt;span class=&quot;hljs-variable&quot;&gt;$TASK_NO&lt;/span&gt;/&quot;&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&quot;&lt;span class=&quot;hljs-variable&quot;&gt;$1&lt;/span&gt;&quot;&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;# GNU sed (Linux)&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# sed -i -e &quot;s/#\[task number\]/$TASK_NO/&quot; &quot;$1&quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;pre class=&quot;aside&quot;&gt;Depending on whether you use BSD sed  (macOS) or GNU sed (Linux), the ~sed~ command will behave slightly differently. For GNU sed, use the commented out line instead of the first one.

There is a slight difference in how you make the two versions of the programs write files in place.&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;git rev-parse --abbrev-ref HEAD&lt;/code&gt; command gives you the name of the current branch, which we then split at the first &lt;code&gt;/&lt;/code&gt; character using &lt;code&gt;cut&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;The next (and last) step is a simple &lt;code&gt;sed&lt;/code&gt; replacement, replacing the &lt;code&gt;#[task number]&lt;/code&gt; string with the branch&apos;s task number.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;$1&lt;/code&gt; variable at the very end of the last line is the name of the commit message file and is something the script receives automatically. We use this to tell &lt;code&gt;sed&lt;/code&gt; what file to replace the text in.&lt;/p&gt;&lt;p&gt;And for the curious, these are all the variables you get access to in the &lt;code&gt;prepare-commit-msg&lt;/code&gt; hook (taken from the &lt;code&gt;prepare-commit-msg.sample&lt;/code&gt; file):&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;COMMIT_MSG_FILE=&lt;span class=&quot;hljs-variable&quot;&gt;$1&lt;/span&gt;
COMMIT_SOURCE=&lt;span class=&quot;hljs-variable&quot;&gt;$2&lt;/span&gt;
SHA1=&lt;span class=&quot;hljs-variable&quot;&gt;$3&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Caveats&lt;/h2&gt;&lt;p&gt;There is a pretty significant exception to when this script does what you want it to: when you&apos;re still on the master branch, where commit messages will start with the text &lt;code&gt;master&lt;/code&gt;. I considered adding a special case for this, but then realized that it&apos;s actually quite helpful in that it helps me remember when I should branch off, so I decided to keep it for now.&lt;/p&gt;&lt;p&gt;Another drawback is that because the commit message appears different from what git expects to find on disk (presumably), it will assume you put an actual message in and complete the commit. At least that&apos;s what I found when using Vim. A simple workaround is deleting everything in the buffer (&lt;code&gt;dae&lt;/code&gt; if you use the awesome &lt;a href=&quot;https://github.com/kana/vim-textobj-entire&quot;&gt;text-obj-entire&lt;/a&gt; plugin) before exiting. Most of the time, though, I use &lt;a href=&quot;https://magit.vc/&quot;&gt;Magit&lt;/a&gt; with Emacs, where canceling the commit works as expected.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Alternate approach&lt;/h2&gt;&lt;p&gt;While I have opted for modifying the commit message before it&apos;s shown to the user, you could potentially also have the machine add the id automatically in the &lt;code&gt;pre-commit&lt;/code&gt; hook.&lt;/p&gt;&lt;p&gt;You would make the system check the message for a pattern and amend the commit with the expected issue id if it&apos;s not present.&lt;/p&gt;&lt;p&gt;This solution doesn&apos;t give you any way to verify whether it&apos;s correct or not, though, so you&apos;d probably want some sort of way to bypass it.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Change your git comment character]]></title><description><![CDATA[In which we look at how we can change our comment characters for git, allowing us to start commit, tag, and any other messages with any character we might fancy, including hashes.]]></description><link>https://blog.thomasheartman.com/posts/change-your-git-comment-character</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/change-your-git-comment-character</guid><pubDate>Mon, 19 Aug 2019 06:21:57 GMT</pubDate><content:encoded>&lt;p&gt;You prepare to commit your files, having made sure that all the right changes are in, that they belong to one logical change, and that you have the id of the task that they belong to. Your editor opens up and you see those familiar commit message instructions, but wait! You suddenly remember that you should start your commit with the id of the task prepended with a &lt;code&gt;#&lt;/code&gt; character, but that would lead git to think that that line is a comment.&lt;/p&gt;&lt;p&gt;How do we solve this?&lt;/p&gt;&lt;p&gt;Easy! We simply tell git not to use the &lt;code&gt;#&lt;/code&gt; character for comments, but pick a different character instead.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;In short&lt;/h2&gt;&lt;p&gt;There&apos;s two ways to do it, both producing the same result. You can either run a command from the command line or edit your git config directly. In this case, imagine we want to use a semicolon (&lt;code&gt;;&lt;/code&gt;).&lt;/p&gt;&lt;p&gt;Command line:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git config --&lt;span class=&quot;hljs-built_in&quot;&gt;local&lt;/span&gt; core.commentChar &lt;span class=&quot;hljs-string&quot;&gt;&apos;;&apos;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Directly modifying your git config file:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-toml&quot;&gt;&lt;span class=&quot;hljs-section&quot;&gt;[core]&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;commentChar&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;;&quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Motivation&lt;/h2&gt;&lt;p&gt;So why might you want to do this? As mentioned in the introduction, maybe your team has a standard format for commit messages, where each commit should lead with the id of the task that the commit relates to.&lt;/p&gt;&lt;p&gt;We use GitLab at work, where if you put a number after a &lt;code&gt;#&lt;/code&gt; in your commit message, it will create a link to the issue with that id, which also adds an entry to the history of said issue. In addition to this, if all commits are prefaced with the task id, it becomes very easy to find out what task a commit relates to when looking at the history.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;What might go wrong?&lt;/h2&gt;&lt;p&gt;This is such a simple modification that there&apos;s not much you need to be aware of, but if you try and use a comment character consisting of more than one character, git will fail when you try and invoke a command:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;error: core.commentChar should only be one character
fatal: bad config variable &lt;span class=&quot;hljs-string&quot;&gt;&apos;core.commentchar&apos;&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; file &lt;span class=&quot;hljs-string&quot;&gt;&apos;.git/config&apos;&lt;/span&gt; at line 6&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Finishing thoughts&lt;/h2&gt;&lt;p&gt;It&apos;s a simple thing, but it&apos;s one of those things that improves your life just that little bit. You can even combine it with the custom config we mentioned last time to have this apply to all repos in your work directory, new &lt;i&gt;and&lt;/i&gt; old.&lt;/p&gt;&lt;p&gt;Now as a final thought, what should you pick as a comment character? It&apos;s really up to what you need for your specific use case, but I find that &lt;code&gt;;&lt;/code&gt; is very rarely something that you&apos;ll want to start your sentences with, so that&apos;s my go-to.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Modularizing your git config with conditional includes]]></title><description><![CDATA[In which we figure out how to conditionally change our git configurations depending on what directory we're working in, saving us from having to go back and rewrite commits to change the author.]]></description><link>https://blog.thomasheartman.com/posts/modularizing-your-git-config-with-conditional-includes</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/modularizing-your-git-config-with-conditional-includes</guid><pubDate>Mon, 12 Aug 2019 08:27:09 GMT</pubDate><content:encoded>&lt;p&gt;Do you track your git config across machines or keep it in sync with your dotfiles? Is it full of settings that you want to share between all your different contexts? Are there certain things that you want to change depending on what the context is? Well, I&apos;ve got news for you!&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;tl;dr:&lt;/h2&gt;&lt;p&gt;If you want to use an additional config file for all subdirectories below a certain path, use the &lt;code&gt;includeIf&lt;/code&gt; functionality that was introduced in git 2.13.0.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-git&quot;&gt;[includeIf &quot;gitdir:&amp;#x3C;path to top directory to use the config in&gt;/&quot;]
path = &amp;#x3C;path to extra config&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That&apos;s all you need to get going, but if you want to know more about how this works and some caveats you might to be aware of, keep reading.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;&lt;code&gt;include&lt;/code&gt; and &lt;code&gt;includeIf&lt;/code&gt;&lt;/h2&gt;&lt;p&gt;First off, I&apos;d be remiss not to direct you to the official documentation for this feature, which can be found &lt;a href=&quot;https://git-scm.com/docs/git-config#_conditional_includes&quot;&gt;here&lt;/a&gt;. However, there&apos;s loads more info there than you might need (and want), so let&apos;s extract the important bits.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;include&lt;/code&gt; and &lt;code&gt;includeIf&lt;/code&gt; sections work the same, except the &lt;code&gt;includeIf&lt;/code&gt; has a condition that must be satisfied. They let you &lt;strong&gt;insert configuration from another file&lt;/strong&gt; into your main one.&lt;/p&gt;&lt;p&gt;In my case, this meant that I could automatically change my email whenever the git directory was a subdirectory of &lt;code&gt;~/projects/work&lt;/code&gt;, allowing me a simple and efficient way to always use my work email for work, without changing my global git config or branching off from my main dotfiles repo.&lt;/p&gt;&lt;p&gt;Here&apos;s the relevant extract from my config:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-git&quot;&gt;[includeIf &quot;gitdir:~/projects/work/&quot;]
path = ~/projects/work/.gitconfig&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;I keep a separate config file in the &lt;code&gt;~/projects/work&lt;/code&gt; directory that overrides my email.&lt;/p&gt;&lt;p&gt;This would also be useful if your team has specific rules about whitespace, merge strategies, comment characters, etc. that you want to enforce.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Things that might trip you up&lt;/h2&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Syntax&lt;/dt&gt;&lt;dd&gt;Note the trailing slash after the directory path in the &lt;code&gt;includeIf&lt;/code&gt; line. This makes it so that it will match all subdirectories of the specified directory. As explained by the docs:&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;blockquote&gt;If the pattern ends with ~/~, ~**~ will be automatically added. For example, the pattern ~foo/~ becomes ~foo/**~. In other words, it matches &quot;foo&quot; and everything inside, recursively.&lt;/blockquote&gt;&lt;p&gt;This also means that &lt;strong&gt;if there is no trailing slash, it&apos;ll match only that specific directory&lt;/strong&gt;.&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;File insertion&lt;/dt&gt;&lt;dd&gt;Here&apos;s another quote from the documentation:&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;blockquote&gt;The contents of the included file are *inserted immediately, as if they had been found at the location of the include directive*. If the value of the variable is a relative path, the path is considered to be relative to the configuration file in which the include directive was found.&lt;/blockquote&gt;&lt;p&gt;So you&apos;ll probably want to put the includes at the bottom of your files to make sure the included config isn&apos;t overridden later on in the source file.&lt;/p&gt;&lt;hr&gt;&lt;p&gt;I hope that cleared some things up for you and that you found it useful; I know I did. If you want more in-depth information, see &lt;a href=&quot;https://git-scm.com/docs/git-config#_conditional_includes&quot;&gt;the documentation&lt;/a&gt;.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Let's read: Haskell Programming from First Principles, pt V]]></title><description><![CDATA[In which we look at type constraints and how they relate to typeclasses, currying and partial application, and polymorphism, both parametric and ad-hoc and how we use it in Haskell.]]></description><link>https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-v</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-v</guid><pubDate>Mon, 05 Aug 2019 18:28:46 GMT</pubDate><content:encoded>&lt;p&gt;Oh, hey, it&apos;s you again! Always a pleasure to have you along for the ride. This time, let&apos;s have a deeper look at one of the basic underpinnings of the Haskell language: &lt;i&gt;types&lt;/i&gt;. Being an implementation of a &lt;i&gt;typed&lt;/i&gt; lambda calculus, types are a big part of what makes Haskell Haskell, and a good understanding of them is essential to master the language.&lt;/p&gt;&lt;p&gt;The chapter opens with a couple of pages asking what types are good for and describing how it can help us enforce invariants, avoid (certain types of) bugs, enable compiler optimizations, and reason about our systems.&lt;/p&gt;&lt;p&gt;For this summary, we&apos;ll explore how to constrain argument types to typeclasses, have another dive into currying and partial application, and have another look at polymorphism.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Constraining your types&lt;/h2&gt;&lt;p&gt;Let&apos;s start off by looking at how we can constrain a function&apos;s domain by using typeclasses and how that impacts the function.&lt;/p&gt;&lt;p&gt;By default, when you create a function and you don&apos;t annotate it, the compiler will give it as wide a definition as it can, using the least specific types, constraining it to a typeclass if necessary, but leaving it completely open if possible. Of course, if one or more of the parameters can only be of a concrete type, it will infer that too.&lt;/p&gt;&lt;p&gt;This generalization is why we can define a function for numbers and then use that function for any type that has an instance of &lt;code&gt;Num&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;To add a typeclass constraint to a type signature, specify the typeclasses in before the arguments and separate them with a &lt;i&gt;fat arrow&lt;/i&gt; (&lt;code&gt;=&gt;&lt;/code&gt;). If you have multiple constraints, put them in parentheses and separate them with commas. The below signatures illustrate this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-type&quot;&gt;Num&lt;/span&gt; a =&gt; a -&gt; a -&gt; a

(&lt;span class=&quot;hljs-type&quot;&gt;Num&lt;/span&gt; a, &lt;span class=&quot;hljs-type&quot;&gt;Num&lt;/span&gt; b) =&gt; a -&gt; b -&gt; b

(&lt;span class=&quot;hljs-type&quot;&gt;Ord&lt;/span&gt; a, &lt;span class=&quot;hljs-type&quot;&gt;Num&lt;/span&gt; a) =&gt; a -&gt; a -&gt; &lt;span class=&quot;hljs-type&quot;&gt;Ordering&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The type constraints only show up at the &lt;i&gt;type level&lt;/i&gt; and are never visible at the &lt;i&gt;term level&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;As we&apos;ll see when we talk about polymorphism a bit later, constraining our types like this enables us to create more powerful and specialized functions at the cost of decreasing general applicability.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Currying&lt;/h2&gt;&lt;p&gt;We&apos;ve talked about currying before, but this time it&apos;s given an entire subchapter! If you can&apos;t quite remember what it is, let me give you a quick summary:&lt;/p&gt;&lt;p&gt;Because any function in a lambda calculus can only be applied to &lt;i&gt;one&lt;/i&gt; argument, the way to construct functions that can be applied to multiple arguments is to nest multiple lambdas. Haskell abstracts this away for us and makes it seems like a function can be applied to an arbitrary number of arguments. The only place where this actually shines through is in function signatures, where the function operator (&lt;code&gt;(-&gt;)&lt;/code&gt;) separates the parameters, hinting that it&apos;s actually just a bunch of nested lambdas&lt;/p&gt;&lt;p&gt;This is handy because it allows partial application, allowing us to pass around functions that haven&apos;t been fully applied and add the remaining arguments when it suits us.&lt;/p&gt;&lt;hr&gt;&lt;p&gt;Haskell is curried by default, but it&apos;s possible to &lt;i&gt;uncurry&lt;/i&gt; functions. What does that mean? It means that if you have a function that you need to apply to two arguments, you can turn it into a function that only accepts a single argument: a tuple containing the two expected arguments. The opposite is also true: if you have a function that expects a tuple, you can curry it to turn it into a function expecting two separate arguments.&lt;/p&gt;&lt;p&gt;The type and possible implementation of &lt;code&gt;uncurry&lt;/code&gt; is as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;uncurry&lt;/span&gt; :: (a -&gt; b -&gt; c) -&gt; (a, b) -&gt; c
&lt;span class=&quot;hljs-title&quot;&gt;uncurry&lt;/span&gt; f (x, y) = f x y&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can play around with it a bit:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;uncurriedPlus&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;Num&lt;/span&gt; a =&gt; (a, a) -&gt; a
&lt;span class=&quot;hljs-title&quot;&gt;uncurriedPlus&lt;/span&gt; (x, y) = x + y

&lt;span class=&quot;hljs-comment&quot;&gt;-- uncurriedPlus could also be implemented using the uncurry function:&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;uncurriedPlus&apos;&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;Num&lt;/span&gt; a =&gt; (a, a) -&gt; a
&lt;span class=&quot;hljs-title&quot;&gt;uncurriedPlus&apos;&lt;/span&gt; = uncurry (+)

&lt;span class=&quot;hljs-comment&quot;&gt;-- and in the same way, we could redefine a plus function using curry:&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;plus&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;Num&lt;/span&gt; a =&gt; a -&gt; a -&gt; a
&lt;span class=&quot;hljs-title&quot;&gt;plus&lt;/span&gt; = curry uncurriedPlus&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Can you see how you can implement &lt;code&gt;fst&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; in terms of each other composed with either &lt;code&gt;curry&lt;/code&gt; or &lt;code&gt;uncurry&lt;/code&gt;? Look up the types in the REPL and play around with it a bit if not.&lt;/p&gt;&lt;p&gt;In short:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Curried functions: many nested functions, each taking one argument each&lt;/li&gt;&lt;li&gt;Uncurried functions: one function, many arguments (grouped in a tuple)&lt;/li&gt;&lt;/ul&gt;&lt;hr&gt;&lt;p&gt;&lt;i&gt;Sectioning&lt;/i&gt; makes a little return in this chapter too. Quick reminder: sectioning is partial applications of infix operators or functions, where we can leave out the term on either side and Haskell will cleverly know that we are missing the value to fill it up: &lt;code&gt;(2^) 3&lt;/code&gt; would give $8$, for instance, while &lt;code&gt;(^2) 8&lt;/code&gt; would give 64. Sectioning works for any binary, infix function.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Polymorphism&lt;/h2&gt;&lt;p&gt;Polymorphism was also mentioned last time, but this time we dive a bit deeper into what it is. Our definitions of &lt;i&gt;parametric&lt;/i&gt; and &lt;i&gt;constrained&lt;/i&gt; polymorphism return, and we&apos;re introduced to something called &lt;i&gt;ad-hoc&lt;/i&gt; polymorphism, so let&apos;s recap and explore a bit.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Parametric polymorphism&lt;/strong&gt; is the broadest form of polymorphism, and is when the type variables are fully polymorphic, completely free of any and all constraints. This means that their actual concrete implementation could by &lt;i&gt;anything&lt;/i&gt; and the function would still do what it should. The function will work on &lt;i&gt;any&lt;/i&gt; type. An example of a parametrically polymorphic function is &lt;code&gt;id&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;id&lt;/span&gt; :: a -&gt; a&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Can you tell what it does? When a function is this polymorphic, there is only &lt;i&gt;one&lt;/i&gt; thing it can do, and that is return whatever it receives as an argument. Hmm? Useless, you say? Well, it has its uses, but this is not the time or place to explore them.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Constrained polymorphism&lt;/strong&gt; is when there are certain constraints placed upon the types by specifying that they must belong to a typeclass. This makes the function able to use functions defined for a given typeclass, increasing the number of things the function can do by simultaneously decreasing the number of values it can accept. Any numeric function is a good example of this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;(+) :: (&lt;span class=&quot;hljs-type&quot;&gt;Num&lt;/span&gt; a) =&gt; a -&gt; a -&gt; a&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;strong&gt;Constraining your types&lt;/strong&gt; will give you more power within the function, but a smaller domain of input values. A good rule of thumb would be to always try and make your functions as general and unconstrained as possible to give the caller maximum freedom, but not to be afraid of putting constraints on the inputs when it is required by the task at hand.&lt;/p&gt;&lt;hr&gt;&lt;p&gt;Sometimes you&apos;ll come across something known as a &lt;strong&gt;polymorphic constant&lt;/strong&gt;. In fact, we&apos;ve seen a lot of these already: any time you only specify a literal numeric value without specifying the type, it will be polymorphic until it&apos;s given a more specific type such as by function application.&lt;/p&gt;&lt;hr&gt;&lt;p&gt;Haskell&apos;s &lt;strong&gt;type inference&lt;/strong&gt; is built on extended version of the Damas-Hindley-Milner type system. It will infer the most generally applicable (polymorphic) type that is still correct for your code. But while declaring types might not be necessary, it&apos;s still considered good practice and is recommended.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Definitions&lt;/h2&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Ad-hoc polymorphism&lt;/dt&gt;&lt;dd&gt;Polymorphism that applies one or more typeclass constraints to  a polymorphic type variable.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Higher-order functions&lt;/dt&gt;&lt;dd&gt;these are mentioned in the chapter, but not expanded upon. A higher-order function is a function that either accepts as argument or returns a function when evaluated. &lt;code&gt;map&lt;/code&gt; is probably the poster child for having a function from &lt;code&gt;a&lt;/code&gt; to &lt;code&gt;b&lt;/code&gt; as its first parameter.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Parametricity&lt;/dt&gt;&lt;dd&gt;Parametricity states that the behavior of a function will be uniform across all concrete applications of the function.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Polymorphism&lt;/dt&gt;&lt;dd&gt;In Haskell: type variables that may refer to more than one concrete type. Usually manifested as &lt;i&gt;ad-hoc&lt;/i&gt; or &lt;i&gt;parametric&lt;/i&gt; polymorphism.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Type inference&lt;/dt&gt;&lt;dd&gt;The ability of some programming languages to &lt;i&gt;infer&lt;/i&gt; types from terms (your code) without explicit type annotations.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Type variable&lt;/dt&gt;&lt;dd&gt;A way to refer to an unspecified type or set of types in type signatures.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Typeclass&lt;/dt&gt;&lt;dd&gt;A collection of functions that must be implemented for any type wishing to create an instance of said typeclass. Allows for ad-hoc polymorphism and abstractions.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Next time&lt;/h2&gt;&lt;p&gt;Next up is the chapter on typeclasses, where we&apos;ll finally get an explanation for how all these numeric types work together and look at some basic, easily derivable typeclasses. Stay tuned!&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Let's read: Haskell Programming from First Principles, pt IV]]></title><description><![CDATA[In which we take a look at some basic data types in Haskell, such as numeric types, tuples, and lists. We also look at data declarations, type and data constructors, and if-expressions. This one's quite the mouthful, so grab some supplies and come explore!]]></description><link>https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-iv</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-iv</guid><pubDate>Mon, 29 Jul 2019 04:07:56 GMT</pubDate><content:encoded>&lt;p&gt;Welcome back to yet another foray into the wonderful world of Haskell, where this time, we&apos;re turning our gaze towards basic data types. The book presents this quote by Robin Milner at the start of the chapter:&lt;/p&gt;&lt;blockquote&gt;There are many ways of trying to understand programs. People often rely too much on one way, which is called “debugging” and consists of running a partly-understood program to see if it does what you expected. Another way, which ML advocates, is to install some means of understanding in the very programs themselves.&lt;/blockquote&gt;&lt;p&gt;Note that in this context, &lt;i&gt;ML&lt;/i&gt; is not machine learning, but &lt;a href=&quot;https://www.wikiwand.com/en/ML_(programming_language)&quot;&gt;the language known as ML&lt;/a&gt;. If you don&apos;t know who Robin Milner was (I didn&apos;t), &lt;a href=&quot;https://en.wikipedia.org/wiki/Robin_Milner&quot;&gt;Wikipedia has this to say about him&lt;/a&gt;:&lt;/p&gt;&lt;blockquote&gt;He developed LCF, one of the first tools for automated theorem proving. The language he developed for LCF, ML, was the first language with polymorphic type inference and type-safe exception handling. In a very different area, Milner also developed a theoretical framework for analyzing concurrent systems, the calculus of communicating systems (CCS), and its successor, the pi-calculus.&lt;/blockquote&gt;&lt;p&gt;So I&apos;d say he&apos;s &lt;i&gt;reasonably&lt;/i&gt; influential.&lt;/p&gt;&lt;p&gt;But that&apos;s enough of a history lesson for now. Let&apos;s move on to some more theory, shall we?&lt;/p&gt;&lt;hr&gt;&lt;p&gt;Let&apos;s start right at the beginning: &lt;strong&gt;what are types?&lt;/strong&gt; In short, types are &lt;i&gt;sets&lt;/i&gt; of values, where a set is a collection with no duplicate entries. Every expression---when evaluated---yields a value, and that value has a type. Each type is defined by the members (the values) that &lt;i&gt;inhabit&lt;/i&gt; (are part of) the type. Boolean values, for instance, have two inhabitants: &lt;code&gt;True&lt;/code&gt; and &lt;code&gt;False&lt;/code&gt;. Integers have an infinite number of inhabitants, every integral value from negative infinity to positive infinity.&lt;/p&gt;&lt;p&gt;Types help us group multiple values that have something in common. It could be a specific domain or model or something more abstract. Whatever it is, they let us talk about a set of values under a shared name.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Data declarations&lt;/h2&gt;&lt;p&gt;Data Types in Haskell are defined by &lt;i&gt;data declarations&lt;/i&gt;. Data declarations consist of a &lt;i&gt;type constructor&lt;/i&gt; with belonging &lt;i&gt;data constructors&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;A type constructor is the name of the type, such as &lt;code&gt;Bool&lt;/code&gt; or &lt;code&gt;Int&lt;/code&gt;, and is used in type signatures, or the &lt;i&gt;type level&lt;/i&gt; of your code.&lt;/p&gt;&lt;p&gt;Data constructors are the values that inhabit the type they are defined in, such as  the aforementioned &lt;code&gt;True&lt;/code&gt; and &lt;code&gt;False&lt;/code&gt; for &lt;code&gt;Bool&lt;/code&gt;. These are the values that appear in the logic of your code, at the so-called &lt;i&gt;term level&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;Let&apos;s look at the data declaration of the &lt;code&gt;Bool&lt;/code&gt; data type to make it clearer:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;Bool&lt;/span&gt; = &lt;span class=&quot;hljs-type&quot;&gt;False&lt;/span&gt; | &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;--   [1]    [2]  [3] [4]&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;ol&gt;&lt;li&gt;The name of the type, aka the type constructor. This is what you see in function signatures.&lt;/li&gt;&lt;li&gt;Data constructor for the value &lt;code&gt;False&lt;/code&gt;.&lt;/li&gt;&lt;li&gt;A pipe operator, indicating that this is a sum type (or discriminated union). This tells us that a &lt;code&gt;Bool&lt;/code&gt; value is either &lt;code&gt;False&lt;/code&gt; or &lt;code&gt;True&lt;/code&gt;, but never both.&lt;/li&gt;&lt;li&gt;Data constructor for the value &lt;code&gt;True&lt;/code&gt;.&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;This is a very simple data declaration. Others may take arguments or use &lt;i&gt;product types&lt;/i&gt; instead of sum types, but what they all have in common is the &lt;code&gt;data&lt;/code&gt; keyword followed by the name of the type. Most are followed by an equals operator and a set of data constructors.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Numeric types&lt;/h2&gt;&lt;p&gt;We&apos;ve worked a bit with numeric types previously, but never really looked too deeply at them. They work quite differently in Haskell than what they do in a number of other languages, so let&apos;s see what we can find.&lt;/p&gt;&lt;p&gt;The book lists two categories of numbers, which each have multiple types:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Integral numbers ::&lt;/li&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Int&lt;/dt&gt;&lt;dd&gt;Fixed-precision integer. Has a minimum and a maximum value.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Integer&lt;/dt&gt;&lt;dd&gt;Integer that supports arbitrarily large and small numbers.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;li&gt;Fractional numbers ::&lt;/li&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Float&lt;/dt&gt;&lt;dd&gt;Single precision floating point numbers. Like in most languages, limited in precision.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Double&lt;/dt&gt;&lt;dd&gt;Double-precision floating point number. Twice as many bits as a &lt;code&gt;Float&lt;/code&gt;. Still limited in precision.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Rational&lt;/dt&gt;&lt;dd&gt;Fractional number that represents a ratio of two integers. A value such as &lt;code&gt;x / y :: Rational&lt;/code&gt; will be a value consisting of two &lt;code&gt;Integer&lt;/code&gt; values and represents the ratio of $x$ to $y$. Arbitrarily precise.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Scientific&lt;/dt&gt;&lt;dd&gt;Space efficient and almost arbitrarily precise. Represented using &lt;i&gt;scientific notation&lt;/i&gt;, storing the coefficient as an &lt;code&gt;Integer&lt;/code&gt; and the exponent as an &lt;code&gt;Int&lt;/code&gt;. Because &lt;code&gt;Int&lt;/code&gt; &lt;i&gt;is&lt;/i&gt; bounded, there &lt;i&gt;is&lt;/i&gt; technically a limit to the size of the number, but hitting it is very unlikely. More efficient, but less precise than &lt;code&gt;Rational&lt;/code&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/ul&gt;&lt;p&gt;All these data types have instances of a typeclass called &lt;code&gt;Num&lt;/code&gt; (more about typeclasses in the coming chapters), which lets us use any which one of them for most functions that only require standard operations.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Choosing an integral data type&lt;/h3&gt;&lt;p&gt;As noted above, &lt;code&gt;Integer&lt;/code&gt; can represent arbitrarily large integers, while &lt;code&gt;Int&lt;/code&gt; (and the related &lt;code&gt;Int8&lt;/code&gt;, &lt;code&gt;Int16&lt;/code&gt;, and so forth)  can only express as many as their predefined size allows them, falling back to overflow wrapping if they exceed their limits.&lt;/p&gt;&lt;p&gt;Because of this, the book advises us to always choose &lt;code&gt;Integer&lt;/code&gt; over &lt;code&gt;Int&lt;/code&gt; unless we really understand the limitations and the additional performance has an impact.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Fractional numbers&lt;/h3&gt;&lt;p&gt;Of the common fractional types mentioned above, three of them come bundled with GHC, while the fourth, &lt;code&gt;Scientific&lt;/code&gt;, comes from an external library.&lt;/p&gt;&lt;p&gt;As was the case with the integral numbers, we are advised to stick to the most precise or efficient type we can use. This would usually be &lt;code&gt;Rational&lt;/code&gt; or &lt;code&gt;Scientific&lt;/code&gt;, but for certain scenarios, such as graphics programming, you might want to use &lt;code&gt;Float&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;Certain mathematical operations require the inputs to be fractional rather than just numeric; division being a great example. The type of the division operator is &lt;code&gt;(/) :: Fractional a =&gt; a -&gt; a -&gt; a&lt;/code&gt;. The &lt;code&gt;Fractional a =&gt;&lt;/code&gt; part tells us that this is a &lt;i&gt;typeclass constraint&lt;/i&gt;, and that the type &lt;code&gt;a&lt;/code&gt; &lt;i&gt;must&lt;/i&gt; have an instance of this typeclass.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;Num&lt;/code&gt; typeclass is a &lt;i&gt;supertype&lt;/i&gt; of the &lt;code&gt;Fractional&lt;/code&gt; typeclass, meaning that to create an instance of &lt;code&gt;Fractional&lt;/code&gt;, the type must also define an instance of &lt;code&gt;Num&lt;/code&gt;. In other words: all &lt;code&gt;Fractional&lt;/code&gt; instances are also instances of &lt;code&gt;Num&lt;/code&gt;, while the opposite is not true.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Comparison&lt;/h3&gt;&lt;p&gt;Like most languages, Haskell defines a number of operators to perform comparisons. Most of these are the same as you see in most languages, but the inequality operator may be a bit different. Anyway, for your viewing pleasure, here they are:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;~(&amp;#x3C;)~&lt;/dt&gt;&lt;dd&gt;Less than&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;~(&gt;)~&lt;/dt&gt;&lt;dd&gt;Greater than&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;~(&amp;#x3C;=)~&lt;/dt&gt;&lt;dd&gt;Less than or equal to&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;~(&gt;=)~&lt;/dt&gt;&lt;dd&gt;Greater than or equal to&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;~(==)~&lt;/dt&gt;&lt;dd&gt;Equal to&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;~(/=)~&lt;/dt&gt;&lt;dd&gt;Not equal to&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;The equality operators take two values that have instances of the &lt;code&gt;Eq&lt;/code&gt; typeclass, and the comparison operators take instances of the &lt;code&gt;Ord&lt;/code&gt; typeclass, which is a subclass of &lt;code&gt;Eq&lt;/code&gt;. As such, an &lt;code&gt;Ord&lt;/code&gt; instance can be used with &lt;i&gt;any&lt;/i&gt; of the above operators, while an &lt;code&gt;Eq&lt;/code&gt; instance can only be used with the equality operators.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;&lt;code&gt;if ... then ... else  ...&lt;/code&gt;&lt;/h2&gt;&lt;p&gt;Haskell operates with &lt;i&gt;~if~ expressions&lt;/i&gt;, rather than &lt;i&gt;~if~ statements&lt;/i&gt;. What this means is that the expression itself evaluates to a value; so you can assign a variable to an &lt;code&gt;if&lt;/code&gt; expression, for example.&lt;/p&gt;&lt;p&gt;The syntax is:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;CONDITION&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;then&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;EXPR_A&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;EXPR_B&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;An assignment might look like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;-- the value of a will evaluate to 2&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;let&lt;/span&gt; a = &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;True&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;then&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This is similar to how the ternary operator (&lt;code&gt;?:&lt;/code&gt;) works in most C-like languages, and much in the same way, you &lt;i&gt;must&lt;/i&gt; have an else clause. This is because it is an expression, and an expression &lt;i&gt;must&lt;/i&gt; evaluate to a value.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Tuples&lt;/h2&gt;&lt;p&gt;The &lt;code&gt;Tuple&lt;/code&gt; type is a way to pack multiple values together and pass them around. Tuple syntax is the same at both type and term levels and is easily distinguished from other types by its distinct look: &lt;code&gt;(x, y)&lt;/code&gt;, a set of parentheses surrounding two or more values or types separated by commas.&lt;/p&gt;&lt;p&gt;At the type level, the tuple would contain types---e.g. &lt;code&gt;(Int, Bool)&lt;/code&gt;---, while at the term level, it would contain expressions: &lt;code&gt;(1, True)&lt;/code&gt;,  &lt;code&gt;(x, y)&lt;/code&gt;, etc.&lt;/p&gt;&lt;p&gt;A tuple has a fixed number of &lt;i&gt;constituents&lt;/i&gt; (parts, members). A tuple with two element is called a &lt;i&gt;pair&lt;/i&gt; or a &lt;i&gt;tuple&lt;/i&gt; (&lt;code&gt;(a, b)&lt;/code&gt;), while a three-element tuple is known as a &lt;i&gt;three-tuple&lt;/i&gt; or a &lt;i&gt;triple&lt;/i&gt; (&lt;code&gt;(a, b, c)&lt;/code&gt;). The number of constituents is known as the tuple&apos;s &lt;i&gt;arity&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;The data declaration for a pair can be found by looking up the &lt;code&gt;(,)&lt;/code&gt; operator in the GHCi:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-class&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;data&lt;/span&gt; (,) a b = (,) a b&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This is quite different from what we saw earlier with the &lt;code&gt;Bool&lt;/code&gt; declaration: It takes two parameters, represented by type variables &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt;, and it&apos;s a so-called &lt;i&gt;product type&lt;/i&gt;, rather than a &lt;i&gt;sum type&lt;/i&gt;, meaning that the number of possible combinations is the &lt;i&gt;product&lt;/i&gt; of the number of possible values for each of the types it&apos;s applied to.&lt;/p&gt;&lt;p&gt;The two-element tuple comes with some default convenience functions in Haskell, &lt;code&gt;fst&lt;/code&gt; and &lt;code&gt;snd&lt;/code&gt;, which gets the first or second element of the tuple, respectively. Their type signatures are:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;fst&lt;/span&gt; :: (a, b) -&gt; a
&lt;span class=&quot;hljs-title&quot;&gt;snd&lt;/span&gt; :: (a, b) -&gt; b&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This way to describe the types of the tuples also extends to when we use them in the function implementation, where we can destructure it and name and use the elements directly. The two above functions can be implemented like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;fst&lt;/span&gt; :: (a, b) -&gt; a
&lt;span class=&quot;hljs-title&quot;&gt;fst&lt;/span&gt; (a, b) = a

&lt;span class=&quot;hljs-title&quot;&gt;snd&lt;/span&gt; :: (a, b) -&gt; b
&lt;span class=&quot;hljs-title&quot;&gt;snd&lt;/span&gt; (a, b) = b&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This destructuring and matching on the shape of the data is known as &lt;i&gt;pattern matching&lt;/i&gt;,  and is something we&apos;ll see a lot more of further down the road.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Lists&lt;/h2&gt;&lt;p&gt;We had a little run-in with lists last time, and they&apos;re only barely mentioned in this chapter. The reason is that there&apos;s a full chapter devoted to lists coming up, so we&apos;ll save the deep-dive for then.&lt;/p&gt;&lt;p&gt;The one thing they do mention this time, though, is that, much like tuples, lists have special syntax too, where the type or the values are enclosed in square brackets, e.g. &lt;code&gt;[Integer]&lt;/code&gt; for describing the type of a list of integral values, and &lt;code&gt;[1, 2, 3, 4]&lt;/code&gt; to construct one of them.&lt;/p&gt;&lt;p&gt;As opposed to tuples, they can only take values of a single type, and there is no limit to how many or how few elements a list can have.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Names and variables&lt;/h2&gt;&lt;p&gt;To close off the chapter, there is a little section on naming conventions in Haskell.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Functions&lt;/strong&gt;, when used as parameters, are typically labeled with variables starting with &lt;code&gt;f&lt;/code&gt;, continuing alphabetically (&lt;code&gt;g&lt;/code&gt;, &lt;code&gt;h&lt;/code&gt;, ....). May also have numbers (&lt;code&gt;f1&lt;/code&gt;, &lt;code&gt;f2&lt;/code&gt;) or an ending apostrophe (&lt;code&gt;f&apos;~)---pronounced /f-prime/---if they&apos;re closely related to a function labeled ~f&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;They may also be given variable names that describe what they do, such as a function fetching text from some source being called &lt;code&gt;txt&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Type variables&lt;/strong&gt;, the ones in type signatures, are commonly given names starting from &lt;code&gt;a&lt;/code&gt; and going along alphabetically.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Arguments&lt;/strong&gt; to functions usually go from &lt;code&gt;x&lt;/code&gt;, though they might also have some other letter assigned to serve a mnemonic function (such as &lt;code&gt;n&lt;/code&gt; for a number or &lt;code&gt;r&lt;/code&gt; for the radius of a circle).&lt;/p&gt;&lt;p&gt;Of course, variable names don&apos;t have to be single letters, but in smaller programs they usually are. In more domain-specific code, it might make more sense to use longer names.&lt;/p&gt;&lt;p&gt;If you have a &lt;strong&gt;list of things&lt;/strong&gt;, it&apos;s common to use a name such as &lt;code&gt;xs&lt;/code&gt;, especially if one element from the list might be called &lt;code&gt;x&lt;/code&gt; (as if &lt;code&gt;xs&lt;/code&gt; was the plural form of &lt;code&gt;x&lt;/code&gt;).&lt;/p&gt;&lt;p&gt;This is demonstrated by the commonly seen construct &lt;code&gt;(x:xs)&lt;/code&gt; which is a way to pattern match on a list using the &lt;i&gt;cons operator&lt;/i&gt; we saw last time. This can be used to destructure the list if it has at least one element, assigning the variable &lt;code&gt;x&lt;/code&gt; to the first element, and &lt;code&gt;xs&lt;/code&gt; to the rest of the list:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;sum&lt;/span&gt; :: &lt;span class=&quot;hljs-type&quot;&gt;Num&lt;/span&gt; a =&gt; [a] -&gt; a
&lt;span class=&quot;hljs-title&quot;&gt;sum&lt;/span&gt; [] = &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;sum&lt;/span&gt; (x:xs) = x + sum xs&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The above function will recursively sum a list by first checking whether it&apos;s empty. If it is, it returns $0$. Otherwise, it returns the sum of the current head and the value of the sum of the rest of the list.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Definitions&lt;/h2&gt;&lt;p&gt;To tide us over until next time, this chapter provides a bunch of juicy definitions!&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Tuple&lt;/dt&gt;&lt;dd&gt;An ordered grouping of values. You cannot have a tuple with only one element, but the type &lt;i&gt;unit&lt;/i&gt; or &lt;code&gt;()&lt;/code&gt; can be thought of as a zero-element tuple.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Typeclass&lt;/dt&gt;&lt;dd&gt;A set of operations defined for a polymorphic type. If a type has an instance of a typeclass, it can be used in any function requiring a value of that typeclass. In Haskell, you can only define one instance of any one typeclass for a given data type. In other words, type &lt;code&gt;a&lt;/code&gt; can have at most &lt;i&gt;one&lt;/i&gt; instance of &lt;code&gt;Eq&lt;/code&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Data constructors&lt;/dt&gt;&lt;dd&gt;How we create values that inhabit a type in Haskell. Can be constant values (&lt;code&gt;True&lt;/code&gt;), or take one or more arguments (&lt;code&gt;(,) a b&lt;/code&gt;)&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Type constructors&lt;/dt&gt;&lt;dd&gt;The name of a type. Can only be used in type signatures&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Data declarations&lt;/dt&gt;&lt;dd&gt;Definition of a data type in Haskell. Consists of a type constructor and zero or more data constructors.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Type alias&lt;/dt&gt;&lt;dd&gt;A way to refer to a type constructor or type constant by a different name, usually to communicate something more specific. &lt;code&gt;type Name = String&lt;/code&gt; would let you use &lt;code&gt;Name&lt;/code&gt; in place of &lt;code&gt;String&lt;/code&gt; in your code, allowing you to say something more about what kind of string you want on the type level.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Arity&lt;/dt&gt;&lt;dd&gt;The number of arguments a function accepts. In Haskell (lambda calculus), all functions are actually 1-arity (&lt;i&gt;unary&lt;/i&gt;) due to currying, but we tend to let Haskell abstract that away and think of the total number of arguments needed to fully evaluate the function.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Polymorphism&lt;/dt&gt;&lt;dd&gt;The ability to write code using values that may be one of several, or any, type. There are two types of polymorphism: &lt;i&gt;parametric&lt;/i&gt; and &lt;i&gt;constrained&lt;/i&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;&lt;i&gt;Parametric&lt;/i&gt; polymorphism is when a function can take &lt;strong&gt;any&lt;/strong&gt; type of value because it doesn&apos;t use any information about it. Parametric polymorphism is easily recognised by there being no constraints placed on the type variable.&lt;/p&gt;&lt;p&gt;&lt;i&gt;Constrained&lt;/i&gt; (or &lt;i&gt;bounded&lt;/i&gt;) polymorphism is when the valid set of types is constrained by a typeclass, such as for the equality operators that require their arguments to have an instance of &lt;code&gt;Eq&lt;/code&gt;.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Summary&lt;/h2&gt;&lt;p&gt;Whew; well done for making it to the end! There was a lot to get through this time around, but it&apos;s been very insightful. Next time we&apos;ll be looking more at types in Haskell, exploring constraints and polymorphism.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Let's read: Haskell Programming from First Principles, pt III]]></title><description><![CDATA[In which we learn about how strings are represented in Haskell, start exploring how we work with lists, look at a surprise operator and talk briefly about total vs partial functions.]]></description><link>https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-iii</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-iii</guid><pubDate>Mon, 22 Jul 2019 04:43:39 GMT</pubDate><content:encoded>&lt;p&gt;This will be a rather short and focused post. Chapter 3 of the book doesn&apos;t spring any exciting new concepts on us or cover large topics such as general syntax. Instead it chooses to zoom in on the &lt;code&gt;String&lt;/code&gt; datatype. We look at how they are represented in Haskell and how we can treat them like lists because, spoiler alert: &lt;strong&gt;that&apos;s what they are&lt;/strong&gt;.&lt;/p&gt;&lt;p&gt;Like in all compiled languages that I&apos;ve used, there&apos;s a difference between the data types &lt;code&gt;Char&lt;/code&gt; and &lt;code&gt;String&lt;/code&gt; and how you represent the literals. As is the convention, a &lt;code&gt;Char&lt;/code&gt; is represented using single quotes (~&apos;a&apos;~), while a string uses double quotes: ~&quot;hey, tiger&quot;~.&lt;/p&gt;&lt;p&gt;However, unlike in a most languages I&apos;m aware of, a &lt;code&gt;String&lt;/code&gt; is actually just syntactic sugar for a linked list of characters (&lt;code&gt;[Char]&lt;/code&gt;). So &lt;code&gt;[&apos;h&apos;, &apos;e&apos;, &apos;l&apos;, &apos;l&apos;, &apos;o&apos;]&lt;/code&gt; and ~&quot;hello&quot;~ are just two ways of writing the exact same thing. This has some interesting effects on how we handle strings, in that it means anything we can do with a list, we can do with a string, but it also means that certain operations will be very costly. There &lt;i&gt;are&lt;/i&gt; alternatives for when you need performance, but let&apos;s not concern ourselves with that for now.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;String/list operations&lt;/h2&gt;&lt;p&gt;In the introduction to handling strings (secretly lists), we are introduced to the functions &lt;code&gt;head&lt;/code&gt;, &lt;code&gt;tail&lt;/code&gt;, &lt;code&gt;take&lt;/code&gt;, &lt;code&gt;drop&lt;/code&gt;, and the operator &lt;code&gt;!!&lt;/code&gt;, so let&apos;s have a quick look at what they do.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;head&lt;/code&gt; and &lt;code&gt;tail&lt;/code&gt; functions return the first element of the list and the list without the first element respectively; so that if you take the &lt;code&gt;head&lt;/code&gt; of a list, the &lt;code&gt;tail&lt;/code&gt; of a list, and then put them back together, you&apos;d have the original list back:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;splitAndPutBackTogether&lt;/span&gt; list =
  &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; h = head list
      t = tail list
   &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; h : t&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;i&gt;Side note: this is the first time we&apos;re seeing that ~:~ operator. It&apos;s known as ~cons~ and it adds a value to the front of a list.&lt;/i&gt;&lt;/p&gt;&lt;p&gt;Be aware that these functions---~head~ and &lt;code&gt;tail&lt;/code&gt;---are &lt;strong&gt;not total&lt;/strong&gt;, and &lt;i&gt;will&lt;/i&gt; throw exceptions at you if you give them an empty list.&lt;/p&gt;&lt;pre class=&quot;aside&quot;&gt;A *total function* is one that is well defined and gives you a result for every input value---i.e. maps every value from the /domain/ into a value in the /image/ (the subset of the /codomain/ containing possible output values), to use the terminology from chapter one.

Functions that are defined only for a subset of their valid arguments are known as *partial functions*.

More on this later on in the book.&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;take&lt;/code&gt; and &lt;code&gt;drop&lt;/code&gt; functions, though, &lt;i&gt;are&lt;/i&gt; total, and will not throw anything in your face. They operate on lists, take an &lt;code&gt;Int&lt;/code&gt; as the first argument and then split the list after as many elements as specified by the &lt;code&gt;Int&lt;/code&gt;, giving you either the first portion or the second. They&apos;re pretty much like &lt;code&gt;head&lt;/code&gt; and &lt;code&gt;tail&lt;/code&gt;, except you can choose how many elements go in each pile, and you&apos;ll always get a list back. If there aren&apos;t enough elements in the list to reach the specified number, &lt;code&gt;take&lt;/code&gt; will give you back the whole list, and &lt;code&gt;drop&lt;/code&gt; will give you an empty list.&lt;/p&gt;&lt;p&gt;&lt;code&gt;!!&lt;/code&gt; is the index operator and returns the element at the specified index in the list. The equivalent of &lt;code&gt;[n]&lt;/code&gt; in a lot of other languages. Zero-indexed and unsafe: ~&quot;hey&quot; !! 2~ would return ~&apos;y&apos;~, while ~&quot;hey&quot; !! 5~ would crash.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Definitions&lt;/h2&gt;&lt;p&gt;There are only a few interesting definitions in this chapter:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;String&lt;/dt&gt;&lt;dd&gt;a sequence of characters. In Haskell, the &lt;code&gt;String&lt;/code&gt; type is just an alias for a linked list of characters, &lt;code&gt;[Char]&lt;/code&gt;.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Type (or datatype)&lt;/dt&gt;&lt;dd&gt;&quot;A classification of values or data&quot;, such as &lt;code&gt;Int&lt;/code&gt;, &lt;code&gt;Bool&lt;/code&gt;, &lt;code&gt;String&lt;/code&gt;, etc. Notably does not have any behavior associated with it.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Concatenation&lt;/dt&gt;&lt;dd&gt;Joining sequences of values together. Often used with lists, it&apos;s the act of putting one before the other and creating a new list. The operator &lt;code&gt;(++)&lt;/code&gt; takes care of it in Haskell.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;hr&gt;&lt;p&gt;That&apos;s it for this chapter. Next time, we&apos;ll be looking at  &lt;i&gt;basic datatypes&lt;/i&gt;. This is when things start to get interesting, so strap yourself in and get ready.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Let's read: Haskell Programming from First Principles, pt II]]></title><description><![CDATA[In which we look at basic Haskell syntax, are pleasantly surprised at compiler type inference, and learn about operators and variable assignment. We also look at some scary terms like 'weak head normal form'.]]></description><link>https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-ii</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-ii</guid><pubDate>Mon, 15 Jul 2019 07:15:14 GMT</pubDate><content:encoded>&lt;p&gt;Welcome to the second part of reading &lt;i&gt;Haskell Programming from First Principles&lt;/i&gt;. This time around we finally see some actual Haskell code. Sort of. It&apos;s mostly just a tour of Haskell&apos;s basic syntax, along with a brief introduction to the REPL and how that works. As such, let&apos;s do a quick recap of the most essential parts.&lt;/p&gt;&lt;pre class=&quot;aside&quot;&gt;There are quite a few references to /the REPL/ in this article. /REPL/ is short for /read eval print loop/ and is a command line interpreter for a programming language. In our case, GHC&apos;s REPL is invoked by either the ~ghci~ or the ~stack ghci~ command, depending on whether you&apos;re using GHC directly or through Stack.&lt;/pre&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;General notes&lt;/h2&gt;&lt;p&gt;Let&apos;s start with some general notes about how Haskell code works, shall we?&lt;/p&gt;&lt;p&gt;First off, Haskell is a whitespace-sensitive language. Much like in Python, the indentation of your code matters. A lot. However, unlike in Python, indentation doesn&apos;t come in multiples of four. Or two. Or any number, really. Instead, it&apos;s dependent on the code (and as such, tabs are &lt;strong&gt;out&lt;/strong&gt;). As the book states:&lt;/p&gt;&lt;blockquote&gt;The basic rule is that code that is part of an expression should be indented under the beginning of that expression, even when the beginning of the expression is not at the leftmost margin. Furthermore, parts of the expression that are grouped should be indented to the same level.&lt;/blockquote&gt;&lt;p&gt;To make that clearer, let&apos;s have an example:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;calc&lt;/span&gt; x =
  &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; y = x ^ &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;
      z = x - &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;
   &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; x + y + z&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Notice how all the variable assignments line up and how the &lt;code&gt;in&lt;/code&gt; block (or line in this case) is indented one space more than the &lt;code&gt;let&lt;/code&gt; block. Like many languages, Haskell has multiple valid ways to structure your code, so just find a style you like and stick to it. The key thing is: don&apos;t freak out if the indentation isn&apos;t what you expect at first.&lt;/p&gt;&lt;p&gt;Point two: capitalization matters. Haskell is quite strict about this and won&apos;t compile unless you follow the rules. Functions and variables start with lowercase letters (and conventionally use camelCase for longer identifiers), while types and type constructors (e.g. &lt;code&gt;Bool&lt;/code&gt; and its variants &lt;code&gt;True&lt;/code&gt; and &lt;code&gt;False&lt;/code&gt;, &lt;code&gt;Int&lt;/code&gt;, etc.) are captitalized (and use what&apos;s sometimes known as PascalCase).&lt;/p&gt;&lt;p&gt;Point three: Haskell is &apos;lazy&apos;, or &apos;lazily evaluated&apos; or &apos;non-strict&apos;. What this means is that Haskell won&apos;t evaluate anything until it really needs to. This is why we can work with infinite lists with no problems---unless you try and consume the whole thing, of course.&lt;/p&gt;&lt;p&gt;Remember when we talked about beta normal form and beta reduction in the last chapter? Haskell doesn&apos;t evaluate everything to normal form by default. Instead, it evaluates to what is known as &lt;i&gt;weak head normal form&lt;/i&gt;. Because of referential transparency, it knows that it can compute everything on demand, so until a value is required from an expression, the expression will be left unevaluated. Imagine it&apos;s a pointer to an expression instead of a value, which can be lazily evaluated when it&apos;s first used.&lt;/p&gt;&lt;p&gt;Finally, on comment syntax: Haskell single-line comments start with a double dash (a literal &lt;code&gt;--&lt;/code&gt;, not the Nintendo kart racing kind), while multiline comments are put between &lt;code&gt;{-&lt;/code&gt; and &lt;code&gt;-}&lt;/code&gt;.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Functions&lt;/h2&gt;&lt;p&gt;Now, let&apos;s have a closer look at function definitions. A function definition is made up of the name of the function, the parameters (separated by whitespace), an equals sign, and the expression that is the body. Example:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;add&lt;/span&gt; x y = x + y&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This function takes two arguments---~x~ and &lt;code&gt;y&lt;/code&gt;---and returns the sum. Notice that we don&apos;t say anything about the types here. The compiler is smart enough to figure that out. If we use the REPL  and the &lt;code&gt;:info&lt;/code&gt; (or &lt;code&gt;:i&lt;/code&gt;) command to describe this function, it tells us that the type of the expression is: &lt;code&gt;Num a =&gt; a -&gt; a -&gt; a&lt;/code&gt;. It&apos;s automatically generic for all numeric types (well, all instances of the typeclass &lt;code&gt;Num&lt;/code&gt;, but we&apos;re getting ahead of ourselves). Neat!&lt;/p&gt;&lt;p&gt;We won&apos;t be looking any deeper into type annotations and function signatures for the time being. They&apos;re not covered in this chapter, but do show up later; so if all the arrows in the the type signature above confuse you: don&apos;t worry.&lt;/p&gt;&lt;p&gt;It&apos;s also worth mentioning that, much like lambda calculus, Haskell uses curried functions. If you forgot what that means,  the authors describe it like this: &quot;In Haskell, when it seems we are passing multiple arguments to a function, we are actually applying a series of nested functions, each to one argument.&quot; Because we return a new function for each argument we apply, we can assign the result of a partially applied function to a variable and save it for later, just like we did with the lambda expressions last time.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Operators and infix functions&lt;/h3&gt;&lt;p&gt;In addition to regular functions, Haskell also has &lt;i&gt;operators&lt;/i&gt;. These are a mix of what you&apos;d expect from any programming language (&lt;code&gt;+&lt;/code&gt;, &lt;code&gt;-&lt;/code&gt;, &lt;code&gt;*&lt;/code&gt;, &lt;code&gt;/&lt;/code&gt;, etc.) and more exotic ones (&lt;code&gt;&gt;&gt;=&lt;/code&gt;, &lt;code&gt;&amp;#x3C;$&gt;&lt;/code&gt;). In fact, Haskell lets you define your own operators too. This might sound unconventional to some, but when you realize that a binary operator is really just a binary function placed in between its arguments, it makes a lot of sense.&lt;/p&gt;&lt;p&gt;See, binary operators are what we call &lt;i&gt;infix&lt;/i&gt;, which means that they go in between their arguments. But operators aren&apos;t the only things that can be infix: Any binary function in Haskell can be used as an infix function if you wrap it in backticks (e.g. &lt;code&gt;div 2 2&lt;/code&gt; becomes &lt;code&gt;2 `div` 2&lt;/code&gt;).&lt;/p&gt;&lt;p&gt;Using &lt;i&gt;partially applied&lt;/i&gt; infix operators is called &lt;i&gt;sectioning&lt;/i&gt;. It&apos;s briefly mentioned in the book and there&apos;s also a &lt;a href=&quot;https://wiki.haskell.org/Section_of_an_infix_operator&quot;&gt;very easily understood article on the Haskell wiki&lt;/a&gt; on it, so let&apos;s use an extract from the latter to clarify:&lt;/p&gt;&lt;blockquote&gt;Essentially, you only give one of the arguments to the infix operator, and it represents a function which intuitively takes an argument and puts it on the &quot;missing&quot; side of the infix operator.

 - ~(2^)~ (left section) is equivalent to ~(^) 2~, or more verbosely ~\x -&gt; 2 ^ x~
 - ~(^2)~ (right section) is equivalent to ~flip (^) 2~, or more verbosely ~\x -&gt; x ^ 2~&lt;/blockquote&gt;&lt;p&gt;When working with operators, it&apos;s important to keep in mind the precedence rules. Most of us probably know that multiplication has higher precedence than addition, for instance---which is why $1+3*5$ is $16$ and not $20$---but it&apos;s not always immediately obvious for all operators. In Haskell, precedence is defined as a number between 0 and 9, where higher numbers denote higher precedence. If you ever wonder about a specific operator, you can use the REPL&apos;s &lt;code&gt;:info&lt;/code&gt;  command to get information about precedence for any operator (e.g. &lt;code&gt;:i (*)&lt;/code&gt;).&lt;/p&gt;&lt;p&gt;Most of the operators introduced in this chapter are pretty self-explanatory---don&apos;t worry, the weird ones I referenced before aren&apos;t mentioned---but there is one that is singled out into its own little section: &lt;code&gt;$&lt;/code&gt;. This operator is a little special in that it has a precedence of 0 and that it is defined as &lt;code&gt;f $ a = f a&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;&lt;i&gt;What?&lt;/i&gt;&lt;/p&gt;&lt;p&gt;Indeed, it doesn&apos;t actually do anything, but it&apos;s all about the precedence. This allows us to use this operator to write an expression (&lt;code&gt;a&lt;/code&gt;) after it that will get fed into the expression before it (&lt;code&gt;f&lt;/code&gt;).&lt;/p&gt;&lt;p&gt;&lt;i&gt;Err ... okay? So what&apos;s the point?&lt;/i&gt;&lt;/p&gt;&lt;p&gt;Oh, it helps us avoid parentheses and a lot of nesting of functions. It&apos;s very useful for composition. A contrived example would be:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;-- is the result of the calculation even?&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;-- without the $ symbol&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;even&lt;/span&gt; (&lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; + &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;)

&lt;span class=&quot;hljs-comment&quot;&gt;-- with the $ symbol&lt;/span&gt;
&lt;span class=&quot;hljs-title&quot;&gt;even&lt;/span&gt; $ &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt; + &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;It probably still seems pretty pointless, but you&apos;ll grow to appreciate it as we progress further. Trust me.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Assigning variables in expressions&lt;/h3&gt;&lt;p&gt;As we saw in the first section, you can assign variables with a &lt;code&gt;let&lt;/code&gt; expression, but there is another way too: the &lt;code&gt;where&lt;/code&gt; declaration.&lt;/p&gt;&lt;p&gt;&lt;code&gt;let&lt;/code&gt; introduces an expression, and can thus be used wherever you can use expressions, while &lt;code&gt;where&lt;/code&gt; is a &lt;i&gt;syntactic construct&lt;/i&gt;, and is only valid in certain parts of the code. If you&apos;re in a function, though, both will serve you just fine. These two functions evaluate to the same result:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-haskell&quot;&gt;&lt;span class=&quot;hljs-title&quot;&gt;letFunction&lt;/span&gt; x =
  &lt;span class=&quot;hljs-keyword&quot;&gt;let&lt;/span&gt; y = x + &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;
   &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; y + x

&lt;span class=&quot;hljs-title&quot;&gt;whereFunction&lt;/span&gt; x = y + x
  &lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt;
    y = x + &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Apart from mentioning that a &lt;code&gt;let&lt;/code&gt; expression is just that, an &lt;i&gt;expression&lt;/i&gt;, and that &lt;code&gt;where&lt;/code&gt; is a declaration, the book doesn&apos;t go into any more details of when to prefer one over the other, so neither will we. However, if you&apos;re interested, I encourage you to check out the &lt;a href=&quot;https://wiki.haskell.org/Let_vs._Where&quot;&gt;Let vs. Where article&lt;/a&gt; on the Haskell wiki.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Definitions&lt;/h2&gt;&lt;p&gt;Definition time! This is a selection of the definitions from the end of the chapter, leaving out the definitions not related to what we have touched on.&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Expression&lt;/dt&gt;&lt;dd&gt;Anything that conforms to the Haskell syntax and that can be reduced to a result. In theory, even constants that can not be reduced (such as the number $1$) are expressions, but these are generally referred to as &lt;i&gt;values&lt;/i&gt; in common parlance.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Value&lt;/dt&gt;&lt;dd&gt;A value is an expression that can not be reduced further.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Function&lt;/dt&gt;&lt;dd&gt;A mathematical object that maps a set of inputs (the &lt;i&gt;domain&lt;/i&gt;) to a set of outputs (the &lt;i&gt;codomain&lt;/i&gt;). A transformer of values. It might be interesting to note that the book also mentions that functions can be described as a list of ordered pairs of their inputs and corresponding outputs: Example: A function &lt;code&gt;(^2)&lt;/code&gt; (a simple square function)  defined for natural numbers would start with the entries &lt;code&gt;(0, 0)&lt;/code&gt;, &lt;code&gt;(1, 1)&lt;/code&gt;, &lt;code&gt;(2, 4)&lt;/code&gt;, &lt;code&gt;(3, 9)&lt;/code&gt;&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Infix notation&lt;/dt&gt;&lt;dd&gt;A style of notation where the operator is placed between the operands.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Operators&lt;/dt&gt;&lt;dd&gt;In Haskell: Functions that are infix by default. Must use symbols only.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Conclusion and next time&lt;/h2&gt;&lt;p&gt;Not bad! We&apos;ve seen some actual code this time and played around a bit at the REPL. We learned a bit about the basic syntax and about how operators and infix notation work, about sectioning and the &lt;code&gt;$&lt;/code&gt; operator.&lt;/p&gt;&lt;p&gt;Next time, we&apos;ll be looking at the &lt;code&gt;String&lt;/code&gt; type and how it is implemented in Haskell.&lt;/p&gt;&lt;p&gt;See you then!&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Building a custom NixOS installer]]></title><description><![CDATA[In which we look at how to create custom installers for NixOS, useful for cases where you need or want certain packages available in the installer and where you don't have internet access. A short introduction that gives you pretty much all you'd need.]]></description><link>https://blog.thomasheartman.com/posts/building-a-custom-nixos-installer</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/building-a-custom-nixos-installer</guid><pubDate>Mon, 08 Jul 2019 10:45:52 GMT</pubDate><content:encoded>&lt;p&gt;Just a few days ago, I finally brought my old MacBook Pro (mid-2012 retina) back from the dead and, naturally, wanted to install Linux on it. My main distro being NixOS, that was the obvious choice. However, when I booted into the installer, I found that I had no networking available. After some digging, I found that it was because it needs proprietary Broadcom wi-fi drivers to connect to anything.&lt;/p&gt;&lt;p&gt;The standard NixOS installer is very dependent on an internet connection to download packages and configure your system, so how do you deal with that? Without a wi-fi connection (and no ethernet ports), it&apos;s not like I can just download the drivers either. Luckily, NixOS lets you build your own custom installer ISOs with a selection of packages available.&lt;/p&gt;&lt;p&gt;I found &lt;a href=&quot;https://github.com/NixOS/nixpkgs/issues/15162&quot;&gt;this GitHub issue&lt;/a&gt; that discusses solutions and provides a custom image you can use. The problem is that the provided image is for NixOS 17.03, which uses an older version of Nix (pre-2.0). At first I figured I could just perform the update during the installation or after, but due to the Nix version bump, I was unable to upgrade. Obviously, I had to take matters into my own hands.&lt;/p&gt;&lt;p&gt;Now that I knew I could build my own custom ISOs, I went looking for documentation on it and found &lt;a href=&quot;https://nixos.org/nixos/manual/index.html#sec-building-cd&quot;&gt;the section in the manual&lt;/a&gt; and the &lt;a href=&quot;https://nixos.wiki/wiki/Creating_a_NixOS_live_CD&quot;&gt;wiki article&lt;/a&gt;. They&apos;re both pretty short, but that&apos;s because they don&apos;t need to be any longer: It&apos;s surprisingly easy and straightforward.&lt;/p&gt;&lt;p&gt;Simply create a Nix file that imports their installers and specifiy what packages you want available and any changes you want to make to the system.&lt;/p&gt;&lt;p&gt;The base config file they provide is this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-nix&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# This module defines a small NixOS installation CD.  It does not&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# contain any graphical stuff.&lt;/span&gt;
{config, pkgs, ...}:
{
  &lt;span class=&quot;hljs-attr&quot;&gt;imports&lt;/span&gt; = [
    &amp;#x3C;nixpkgs/nixos/modules/installer/cd-dvd/installation-cd-minimal.nix&gt;

    &lt;span class=&quot;hljs-comment&quot;&gt;# Provide an initial copy of the NixOS channel so that the user&lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;# doesn&apos;t need to run &quot;nix-channel --update&quot; first.&lt;/span&gt;
    &amp;#x3C;nixpkgs/nixos/modules/installer/cd-dvd/channel.nix&gt;
  ];
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can extend this to add our proprietary drivers and even additional packages to have available in the installer. So if you prefer the Fish shell to Bash or want to have access to Git? Yeah, we can do that.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-nix&quot;&gt;{config, pkgs, ...}:
{
  &lt;span class=&quot;hljs-attr&quot;&gt;imports&lt;/span&gt; = [
    &amp;#x3C;nixpkgs/nixos/modules/installer/cd-dvd/installation-cd-minimal.nix&gt;
    &amp;#x3C;nixpkgs/nixos/modules/installer/cd-dvd/channel.nix&gt;
  ];

  &lt;span class=&quot;hljs-comment&quot;&gt;# configure proprietary drivers&lt;/span&gt;
  nixpkgs.config.&lt;span class=&quot;hljs-attr&quot;&gt;allowUnfree&lt;/span&gt; = &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;;
  boot.initrd.&lt;span class=&quot;hljs-attr&quot;&gt;kernelModules&lt;/span&gt; = [ &lt;span class=&quot;hljs-string&quot;&gt;&quot;wl&quot;&lt;/span&gt; ];
  boot.&lt;span class=&quot;hljs-attr&quot;&gt;kernelModules&lt;/span&gt; = [ &lt;span class=&quot;hljs-string&quot;&gt;&quot;kvm-intel&quot;&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&quot;wl&quot;&lt;/span&gt; ];
  boot.&lt;span class=&quot;hljs-attr&quot;&gt;extraModulePackages&lt;/span&gt; = [ config.boot.kernelPackages.broadcom_sta ];

  &lt;span class=&quot;hljs-comment&quot;&gt;# programs that should be available in the installer&lt;/span&gt;
  environment.&lt;span class=&quot;hljs-attr&quot;&gt;systemPackages&lt;/span&gt; = &lt;span class=&quot;hljs-keyword&quot;&gt;with&lt;/span&gt; pkgs; [
    fish
    git
  ];
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Building the image is a simple command. Assuming your file is called &lt;code&gt;iso.nix&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;nix-build &lt;span class=&quot;hljs-string&quot;&gt;&apos;&amp;#x3C;nixpkgs/nixos&gt;&apos;&lt;/span&gt; -A config.system.build.isoImage -I nixos-config=iso.nix&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And that&apos;s it. Now, just flash it onto a drive or burn it onto a disc and you&apos;re off to the races.&lt;/p&gt;&lt;hr&gt;&lt;p&gt;Before rounding out this post, there&apos;s a few things I think it&apos;s worth to be aware of, even if we won&apos;t look too much into them:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;The wiki states that you don&apos;t need an internet connection when using a custom ISO with packages, which makes me think that if you specify in this config all the packages you&apos;ll need (for your final install), you won&apos;t need to download them again when actually installing.&lt;/li&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;code&gt;nix-build&lt;/code&gt; will build the image based on your system&apos;s &lt;code&gt;nixos&lt;/code&gt; Nix channel. I use the unstable branch, so it built an image based on a NixOS 19.09 preview. You can of course change channels in the installer if you want to use a different base for the install (though this would definitely require internet access).&lt;/li&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;del&gt;From what I understand, you need a NixOS system to build one of these images. So if you need one of these but don&apos;t run NixOS already, it seems you&apos;re locked into finding someone who could build the image for you. This isn&apos;t great for onboarding new people, and you&apos;d think that it&apos;d suffice with just the Nix package manager---honestly: it might. I don&apos;t know---but the documentation talks specifically about building using &quot;an existing working NixOS installation&quot;.&lt;/del&gt; As was pointed out to me &lt;a href=&quot;https://www.reddit.com/r/NixOS/comments/cdm18x/on_creating_custom_installers_a_blog_post/etvgk13/?utm_source=share&amp;#x26;utm_medium=web2x&quot;&gt;on Reddit&lt;/a&gt;, you need the Nix package manager to build one of these images, but not necessarily a NixOS system. However, it was also mentioned that it does probably have to be a Linux system, so Nix on macOS likely wouldn&apos;t work.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;And with that: goodbye!&lt;/p&gt;</content:encoded></item><item><title><![CDATA[Emacs, VSCode, and me]]></title><description><![CDATA[In which a close friend gives me some dubious advice and I fall in love with a text editor. Looking at it in retrospect, how does Emacs compare to VSCode, and, if I'd known then what I know now, would I do it again?]]></description><link>https://blog.thomasheartman.com/posts/emacs-vscode-and-me</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/emacs-vscode-and-me</guid><pubDate>Mon, 01 Jul 2019 07:51:32 GMT</pubDate><content:encoded>&lt;p&gt;It was about a year ago. My life was good. I had things in order (mostly). And most importantly: I had an editor I liked. VSCode and I had been going steady for about a year. With its excellent support for Python and JS---which was most of my work in those days---I rarely ever needed to venture into new territory. It felt good. I was happy.&lt;/p&gt;&lt;p&gt;&lt;i&gt;I was happy!&lt;/i&gt;&lt;/p&gt;&lt;p&gt;Then it all came crashing down. A good friend and I decided to hang out and program one Saturday. The sky was a clear blue, the temperature high, and summer was just around the corner. We got into his office, sat down, and started setting up. That&apos;s when it happened. Completely out of left field:&lt;/p&gt;&lt;p&gt;--- &lt;i&gt;So I found this cool thing the other day. It&apos;s called Spacemacs.&lt;/i&gt;&lt;/p&gt;&lt;p&gt;Spacemacs?&lt;/p&gt;&lt;p&gt;--- &lt;i&gt;Yeah, it&apos;s Emacs, but with &quot;evil mode&quot;. So you can get your Vim bindings!&lt;/i&gt;&lt;/p&gt;&lt;p&gt;It&apos;s true. I had been seduced into the deep, dark depths of Vim about a year prior, and had never found my way out. Never tried, really. I had let it consume me, and there was no way I&apos;d let it go. Not for the world. Of course I had been using the VSCode Vim plugin, but while it had given me most of the functionality I wanted, I did sometimes find myself longing for something more. So I thought I ought to at least give this Spacemacs thing a go.&lt;/p&gt;&lt;p&gt;With one eyebrow slightly cocked, I went ahead and downloaded Spacemacs. I had tried to run Emacs previously, but had been met with that sheer, white light that comes as the default, and had been unable to figure out how to even close the program without resorting to my mouse. Naturally, I was skeptical.&lt;/p&gt;&lt;p&gt;So I launch it, resist the white light as I choose &apos;evil mode&apos; and watch the window turn dark. The logo appears. It says it&apos;s loading. Fetching packages. Eventually, the words &quot;Spacemacs is ready&quot; appear at the bottom of the window. I get it up and running and do some basic programming. I don&apos;t know what it is, but something just feels ... &lt;i&gt;good&lt;/i&gt;. I spend the rest of the day with Spacemacs, and when the time comes, I don&apos;t want to let it go. I go home, dreaming of what I&apos;ll do to it. VSCode is nowhere to be found.&lt;/p&gt;&lt;p&gt;That weekend, neither Emacs nor I left my apartment. We were consumed in the fiery throes of passion and configuration, and when the sun rose the following Monday, I knew my heart had been turned.&lt;/p&gt;&lt;hr&gt;&lt;p&gt;In truth, it would be another few weeks before I left VSCode completely and migrated to Emacs even at work, but it was coming. &lt;i&gt;Oh, it was coming&lt;/i&gt;. To this day, I still stay faithful to Emacs for most of my endeavors, only venturing out when there is something I can&apos;t find proper support for (and even then, it&apos;s just a matter of time before I take matters into my own hands!).&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;What I love about it&lt;/h2&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;The extensibility&lt;/dt&gt;&lt;dd&gt;The fact that you can make it do pretty much &lt;i&gt;whatever&lt;/i&gt; you want to is nothing short of amazing. I have never seen an editor this powerful and versatile.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;It&apos;s the &apos;self-documenting editor&apos;&lt;/dt&gt;&lt;dd&gt;Everything in Emacs is documented. You ever wonder what a key does? &lt;code&gt;C-h k &amp;#x3C;key (or combination)&gt;&lt;/code&gt; has got you covered. You wonder what the value of a variable is? &lt;code&gt;C-h v &amp;#x3C;variable name&gt;&lt;/code&gt;. Want help with Emacs? &lt;code&gt;C-h C-h&lt;/code&gt;. &lt;i&gt;Boom.&lt;/i&gt;&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;EXWM&lt;/dt&gt;&lt;dd&gt;The Emacs X Window Manager. Just recently, I finally got it set up to the point where Emacs now manages all of my windows (yes, for &lt;i&gt;all&lt;/i&gt; applications) for me. How many other editors can do that? Your move, /&apos;Code/.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Emacs Lisp&lt;/dt&gt;&lt;dd&gt;I think Lisp is a pretty cool guy. He lets you configure emacs down to the bone. Much like the &lt;i&gt;monarch of beef patties&lt;/i&gt;, he let&apos;s you &apos;have it your way&apos;, and honestly, that&apos;s the way I like it.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;What I&apos;m not crazy about&lt;/h2&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Its single threaded nature&lt;/dt&gt;&lt;dd&gt;This is usually not much of an issue, unless you somehow end up freezing the main thread, which can happen. In that case, best restart your editor.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Lacklustre support for certain languages&lt;/dt&gt;&lt;dd&gt;While most languages I use are very well supported in Emacs, I struggle with others. In particular, Microsoft&apos;s .NET languages have been hard to get set up properly.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Emacs Lisp&lt;/dt&gt;&lt;dd&gt;Yeah, it&apos;s back. Mostly because I don&apos;t really know Lisp yet (relax; it&apos;s on my todo list). Until you&apos;re comfortable with it, it makes changing your config just that little bit trickier.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;What I miss from the VSCode days&lt;/h2&gt;&lt;p&gt;So it&apos;s not &lt;i&gt;all&lt;/i&gt; roses. There are some things I miss from VSCode.&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;The ease of use&lt;/dt&gt;&lt;dd&gt;I can&apos;t really that the learning curve is steeper; getting started with VSCode is just &lt;i&gt;so&lt;/i&gt; easy. Also, installing extensions is a piece of cake.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;The massive amount of plugins&lt;/dt&gt;&lt;dd&gt;Not that Emacs doesn&apos;t have packages, but most communities I see seem to have settled on VSCode as their darling, so that&apos;s just where you&apos;re going to see the most activity and up-to-date plugins in a lot of languages.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;The amount of documentation&lt;/dt&gt;&lt;dd&gt;I mentioned that Emacs is self-documenting. This is great. But it&apos;s also ... over 40 years old (1976?! &lt;i&gt;Gee!&lt;/i&gt;)! So finding documentation online is tricky in comparison.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;The community&lt;/dt&gt;&lt;dd&gt;Everybody loves &lt;del&gt;Raymond&lt;/del&gt; VSCode. That&apos;s great and makes it super easy to find articles on how to set it up and configure it and so on. Need help? Ask &lt;i&gt;anyone&lt;/i&gt;. Chances are they&apos;re using VSCode. The Emacs community is great too, but much, &lt;i&gt;much&lt;/i&gt; smaller.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;hr&gt;&lt;p&gt;In the end, do I regret it? Not for a second. I think it&apos;s a worthwhile tradeoff if you can take the initial learning curve and are willing to put some time into your editor. So if you feel inspired, should &lt;i&gt;you&lt;/i&gt; do it? All I can say is that if you pay the upfront cost, Emacs will return it tenfold.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[QWERTY to Dvorak]]></title><description><![CDATA[In which I look back upon the last two years and see whether learning the Dvorak layout was worth it or not. I discuss the benefits and the drawbacks, whether I think it was worth it and if I'd recommend it, and give a few tips to anyone else looking to do the same.]]></description><link>https://blog.thomasheartman.com/posts/qwerty-to-dvorak</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/qwerty-to-dvorak</guid><pubDate>Mon, 24 Jun 2019 05:55:24 GMT</pubDate><content:encoded>&lt;p&gt;Ever thought about changing up your keyboard layout? Maybe something as small as going from an ISO layout to an ANSI  one (hint: tall and thin to short and fat return key), or from Norwegian (or whichever your language of choice is) to American QWERTY? Maybe something more comprehensive, like learning a whole new layout, such as Dvorak, Colemak, or Workman? Well, I&apos;ve done all of the above, and while the smaller changes can offer some pretty significant benefits, they&apos;re pretty easy to get through. The layout-changes are more interesting. I&apos;d like to talk briefly about how I went from QWERTY to Dvorak and what I learned along the way.&lt;/p&gt;&lt;hr&gt;&lt;p&gt;First off: you might wonder why I&apos;d do that. I&apos;d love to tell you that I had some grand epiphany and suddenly realized that the QWERTY life wasn&apos;t worth living or that I discovered that Mr Dvorak himself was actually my great-great-grandfather; but nah, it was actually just an offhand comment someone made.&lt;/p&gt;&lt;p&gt;See, I had just recently started learning Vim and was talking about it with some fellow students when one of them jokingly suggested I do it in Dvorak instead. As if it wasn&apos;t challenging enough already, right? I laughed it off at first, but it sparked something in me. Thirty minutes and some googling later and I had made my mind up. I didn&apos;t know whether I was gonna make the switch, but I knew I had to check it out to see what all the fuss was about.&lt;/p&gt;&lt;p&gt;Before starting my degree in computer science (about two years prior to that fateful comment), I had never been much into computers and never properly learned to type, so my keyboard skills weren&apos;t exactly award-winning: I wasn&apos;t very fast (though not remarkably slow either), and I quite often had to look at the keyboard to find the key I was looking for.&lt;/p&gt;&lt;p&gt;Taking the above into consideration, I realized this was a chance to learn proper form and improve my typing skills; so after some investigation, I decided I was gonna go for it. And seeing this as a chance to pick a layout designed specifically for my purposes, I decided to go for the &lt;a href=&quot;https://www.kaufmann.no/roland/dvorak/&quot;&gt;Programmer Dvorak&lt;/a&gt; layout.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Pros and cons&lt;/h2&gt;&lt;p&gt;Now, about two years and thousands of key strokes later, I can take stock of what I have gained from switching and what issues arose because of it.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Benefits&lt;/h3&gt;&lt;p&gt;Proper touch typing form: This might not seem like a big one, and from what I understand, it&apos;s not necessarily the holy grail that some people make it out to be, but it has been a big boon to me. I can&apos;t comment on it being better or more efficient than any other technique, but it sure beats my original, awkward, four-fingered approach.&lt;/p&gt;&lt;p&gt;Speed: My typing speed has gone up dramatically. I don&apos;t know how many words per minute I could get out of my old QWERTY skills, but it wasn&apos;t breaking any necks. I reckon that after about 3--4 months of Dvorak I had already caught up.&lt;/p&gt;&lt;p&gt;Accuracy: A nice feature of learning Dvorak on keyboards where you can&apos;t change the physical layout is that you need to memorize the layout because---with the exception of &apos;A&apos; and &apos;M&apos;---no letters are placed in the same spot. A side effect of this is that you can&apos;t look down on the keyboard to find a key. In fact, that&apos;ll probably just confuse you further.&lt;/p&gt;&lt;p&gt;Comfort: There&apos;s something about the alternating hand-motion of the Dvorak layout that I really like. In fact, while learning it, I&apos;d often come across sequences of letters that just felt &lt;i&gt;good&lt;/i&gt; to write.&lt;/p&gt;&lt;p&gt;It &lt;i&gt;might&lt;/i&gt; be more ergonomic: You often hear that the Dvorak layout is more ergonomic and better for avoiding RSI and the like. I can&apos;t comment on the veracity of these claims, but it sounds plausible.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Drawbacks&lt;/h3&gt;&lt;p&gt;The ramp-up time: It took a while until I got up to a respectable speed. This period where things just don&apos;t move as fast as you want can be annoying and mentally taxing.&lt;/p&gt;&lt;p&gt;Extra set-up time: Dvorak is by no means the default layout for any system (as far as I&apos;m aware), and so---if you&apos;re using a software-defined layout---you&apos;ll always need to go through some extra steps to set it up properly. Even more so if you go for some esoteric layout like Programmer Dvorak (though Linux comes with this available out of the box). This can of course be offset by going for a programmable keyboard (or getting a Dvorak keyboard).&lt;/p&gt;&lt;p&gt;Pair programming: If you&apos;re getting help from a coworker, keep a QWERTY layout handy. It&apos;s okay to have a little laugh when they stand there, though, perplexed at why nothing seems to work.&lt;/p&gt;&lt;p&gt;Losing touch with QWERTY: When I switched, I switched completely. As a result of this, every time I use a QWERTY keyboard now, I need to go looking for keys and I&apos;m super slow. Though, for some reason, this does not apply to phone keyboards, where Dvorak feels awkward but QWERTY is perfectly fine.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Is it worth it?&lt;/h2&gt;&lt;p&gt;&lt;strong&gt;Absolutely&lt;/strong&gt;.&lt;/p&gt;&lt;p&gt;Seeing as I spend most of my day using a keyboard, it makes sense to invest in building skills. This might be &apos;survivor bias&apos; talking, but I got so much out of it that I&apos;d recommend it to anyone who&apos;s interested. At least have a little sniff. If you&apos;ve got the time and energy, it can be very fun and offer a real feeling of accomplishment. Plus, it&apos;ll keep your brain active!&lt;/p&gt;&lt;p&gt;If that was all you wanted to know, you can stop reading now, but if you&apos;re looking for some tips on how to learn a new layout, let&apos;s finish it off with what I found worked for me.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;How to learn&lt;/h2&gt;&lt;p&gt;After picking my target layout (Programmer Dvorak), I had to find out how to learn. While it might be tempting to just sit down with a key map next to you (or shuffle the physical keys around if you can do that) and go for it, this is quite likely to be counterproductive for a number of different reasons; the biggest ones being that you&apos;re more likely to slip out of proper technique and that it&apos;s less efficient (based on my empirical studies with a sample size of one) when it comes to memorizing layout.&lt;/p&gt;&lt;p&gt;So what do I recommend? Glad you asked! I&apos;ve got some tips for ya:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Use typing training software&lt;/dt&gt;&lt;dd&gt;These will typically introduce you to one new letter for each hand at a time and slowly work their way through the full layout, often focusing on common patterns. If you want tips on which one to go for, I&apos;d recommend &lt;a href=&quot;https://www.typingclub.com/&quot;&gt;Typing Club&lt;/a&gt;; it&apos;s free, effective, and even includes some pretty interesting bits of writing to copy as you progress, so you can learn while you learn. &lt;i&gt;Yo, dawg.&lt;/i&gt;&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Take it everywhere (work, studies, whatever)&lt;/dt&gt;&lt;dd&gt;Once you&apos;re comfortable enough with the position of the keys to not feel like you need to look up where a key is before pressing it (though thinking is okay), start using it all the time. Once you&apos;ve got the basics down, the most important thing is to get exposure and experience with it. Depending on your situation, this can be more or less acceptable, so keep important deadlines and the like in mind, but don&apos;t let that stop you. Keep your other layout around so you can swap back in case of emergency (or pair programming!).&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Don&apos;t give up!&lt;/dt&gt;&lt;dd&gt;Even when it seems hard and you&apos;re tired of making the same typo for the two hundred and twenty-seventh time this hour, stick with it. Take a deep breath, have a cup of tea, and clear your mind. Go back to the keyboard and start again. Consistency is key. This goes doubly for memorizing fingerings and modified keys: Make sure you always hit the key with the correct finger. Some keys might be awkward at first, but you&apos;ll get used to it eventually.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Accurate is the new fast&lt;/dt&gt;&lt;dd&gt;It doesn&apos;t matter how fast you are if you hit the wrong key half the time. It&apos;s important to focus on accuracy, especially at the start. Speed will come.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;If you decide to embark on this exciting journey, be aware: it won&apos;t be easy and the learning curve is pretty steep; but it&apos;s not as difficult as you might think. Time and tenacity is all you need: Once you start, you simply need to stick with it.&lt;/p&gt;&lt;p&gt;Good luck!&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Let's read: Haskell Programming from First Principles, pt I]]></title><description><![CDATA[In which I finally find the time to dive into learning Haskell from first principles. Turns out 'first principles' mean understanding the mathematical underpinnings of the language before I ever get to touch (or even see) any code.]]></description><link>https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-i</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/lets-read-haskell-programming-from-first-principles-pt-i</guid><pubDate>Sun, 16 Jun 2019 16:36:21 GMT</pubDate><content:encoded>&lt;p&gt;So you wanna learn Haskell, huh? Well, you&apos;ve come to the right place. Maybe.&lt;/p&gt;&lt;p&gt;This is the first in a series of posts where I try to firm up my understanding of the Haskell programming language by going through the book &lt;i&gt;Haskell Programming from First Principles&lt;/i&gt; by Christopher Allen and Julie Moronuki (ISBN: 9781945388033). I&apos;ll work my way through the book and write a summary of the most important bits from each chapter as I go along.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;A little bit of background&lt;/h2&gt;&lt;p&gt;For a while now, I&apos;ve been very interested in Haskell and using it whenever I can for my side projects, but I&apos;ve also been very busy, and haven&apos;t had as much time to play with it as I&apos;d wish. I read &lt;a href=&quot;http://learnyouahaskell.com/&quot;&gt;Learn You a Haskell for Great Good&lt;/a&gt; and far too many monad tutorials when I first started out, but since then, it&apos;s mostly been a just-in-time sort of process when looking for answers to problems I&apos;ve come across. So, while I feel I have a basic grasp of the language, some of the more advanced features still escape me.&lt;/p&gt;&lt;p&gt;This book has been on my reading list for a while, but I&apos;ve not made a serious effort to get through it before. Now, though, I have the time and I have the motivation. It&apos;s time to learn Haskell. For real.&lt;/p&gt;&lt;p&gt;Alright, here we go. Deep breaths.&lt;/p&gt;&lt;p&gt;&lt;i&gt;Deep breaths.&lt;/i&gt;&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Chapter 1: All you need is Lambda&lt;/h2&gt;&lt;p&gt;.... aaaand there&apos;s not a single line of Haskell in this whole chapter.&lt;/p&gt;&lt;p&gt;I&apos;m sorry to disappoint you, dear reader, but this chapter is entirely about the theoretical underpinnings of the Haskell language: the &lt;i&gt;lambda calculus&lt;/i&gt;. But that doesn&apos;t mean that we can&apos;t make anything of it! Quite the opposite, in fact.&lt;/p&gt;&lt;p&gt;So put on your math hat and do some light stretches.&lt;/p&gt;&lt;p&gt;...&lt;/p&gt;&lt;p&gt;Ready?&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Lambda calculus&lt;/h2&gt;&lt;p&gt;While a thorough introduction to the lambda calculus is outside the scope of this post (not to mention, &lt;i&gt;not something I&apos;m qualified to do&lt;/i&gt;), there are certain concepts that would aid our learning, so let&apos;s try a basic introduction.&lt;/p&gt;&lt;p&gt;In the summary of the first chapter, the lambda calculus is defined as &quot;a formal system for expressing programs in terms of abstraction and application.&quot; Wow. Such clarity.&lt;/p&gt;&lt;p&gt;Let&apos;s see if we can find something more digestible.&lt;/p&gt;&lt;p&gt;Earlier on, the book defines &lt;i&gt;a&lt;/i&gt; calculus as a method of calculation or reasoning. In other words, it&apos;s a system we can use to solve problems. The &lt;i&gt;lambda&lt;/i&gt; calculus is but one process for formalizing one of these methods or systems. In other words, it&apos;s a way of thinking about and calculating certain problems and it gives you a set of tools that you can use to solve these.&lt;/p&gt;&lt;p&gt;So why are we looking at the lambda calculus before getting into the code? Well, because functional programming is made up of expressions (values, variables,  functions) that model typical mathematical behavior, and understanding how they interact will help us understand how the language works later. Or something.&lt;/p&gt;&lt;p&gt;That&apos;s about as much as you&apos;ll need to get started. We&apos;ll cover anything else as and when it comes up.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Lambda terms&lt;/h2&gt;&lt;p&gt;Let&apos;s talk about &lt;i&gt;lambda terms&lt;/i&gt;, the three basic components of the lambda calculus. They are:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Variables&lt;/dt&gt;&lt;dd&gt;A &lt;i&gt;variable&lt;/i&gt; is just something you can assign a value to. It has no meaning or value, but only exists as potential input to a function. Simple.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Abstractions&lt;/dt&gt;&lt;dd&gt;An &lt;i&gt;abstraction&lt;/i&gt; is a function. It is a lambda term that has a &lt;i&gt;head&lt;/i&gt; (a &lt;i&gt;lambda&lt;/i&gt; (𝜆) followed by a variable name) and a &lt;i&gt;body&lt;/i&gt; (another expression) and is applied to an &lt;i&gt;argument&lt;/i&gt;. An argument is an input value.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Expressions&lt;/dt&gt;&lt;dd&gt;An &lt;i&gt;expression&lt;/i&gt; can be a variable name, an abstraction, or any combination of those two.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;A function in the lambda calculus is nothing special. It&apos;s just an expression that can be applied to another expression and that returns yet another expression. If this sounds confusing, keep in mind that expressions can be both values and other functions.&lt;/p&gt;&lt;p&gt;A lambda abstraction (that is, a function) looks like this:&lt;/p&gt;&lt;p&gt;$𝜆x.x$&lt;/p&gt;&lt;p&gt;where everything from the $𝜆$ to the \(.\) (\(𝜆x.\)) is known as the &lt;i&gt;head&lt;/i&gt;, and the &lt;i&gt;body&lt;/i&gt; is what comes after the \(.\) ($x$ in this case). The head &lt;i&gt;binds&lt;/i&gt; variables to be used in the body (i.e. function parameters).&lt;/p&gt;&lt;p&gt;Now, an interesting thing to note is that each lambda can only take one argument. Does that mean that in lambda calculus you can only have functions that take a single argument?&lt;/p&gt;&lt;p&gt;Not quite. See, functions that take multiple arguments are actually just nested heads:&lt;/p&gt;&lt;p&gt;$𝜆x.𝜆y.xy$&lt;/p&gt;&lt;p&gt;But this is quite verbose, so we&apos;ll simplify it by simply writing&lt;/p&gt;&lt;p&gt;$𝜆xy.xy$&lt;/p&gt;&lt;p&gt;It might seem trivial but it is a very important property of lambdas, known as currying (after Haskell Curry (no, &lt;i&gt;really&lt;/i&gt;)).&lt;/p&gt;&lt;p&gt;This is also what allows for partial application. Because an expression can be partially evaluated, we can also apply it to one value and get a new function back.&lt;/p&gt;&lt;p&gt;For a concrete example, let&apos;s say we have a function $mul$ that takes two arguments and returns their product:&lt;/p&gt;&lt;p&gt;$mul=𝜆xy.x*y$&lt;/p&gt;&lt;p&gt;If we want to create a function that doubles a value, we can do that by applying $mul$ to $2$:&lt;/p&gt;&lt;p&gt;$double=mul(2)$&lt;/p&gt;&lt;p&gt;or, written out as the result of the above expression:&lt;/p&gt;&lt;p&gt;$double=𝜆y.2*y$&lt;/p&gt;&lt;p&gt;The $double$ function expects one argument and will return the double of whatever it receives and is defined as a partially applied $mul$.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Glossary&lt;/h2&gt;&lt;p&gt;How lambda terms interact is probably the most important part of this chapter, but let&apos;s have a look at some other terms mentioned in the chapter---mostly because you can use them to sounds smart on internet message boards, but also because they help us understand what we&apos;re talking about when we&apos;re talking about the lambda calculus.&lt;/p&gt;&lt;ul&gt;&lt;div&gt;&lt;dt&gt;Alpha equivalence&lt;/dt&gt;&lt;dd&gt;Two expressions are &lt;i&gt;alpha equivalent&lt;/i&gt; if they are the same function, even if they are written with different symbols. The following functions are alpha equivalent:&lt;/dd&gt;&lt;/div&gt;&lt;ul&gt;&lt;li&gt;$𝜆a.a$&lt;/li&gt;&lt;li&gt;$𝜆b.b$&lt;/li&gt;&lt;li&gt;$𝜆c.c$&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;&lt;dt&gt;Application&lt;/dt&gt;&lt;dd&gt;How we evaluate/reduce lambdas.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Beta normal form&lt;/dt&gt;&lt;dd&gt;When an expression cannot be &lt;i&gt;beta reduced&lt;/i&gt; any further, either because there are no more application to do (no more lambdas), or because there are no free variables to apply the function to.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Beta reduction&lt;/dt&gt;&lt;dd&gt;Evaluating expressions. This is what happens when you go from the expression&lt;/dd&gt;&lt;/div&gt;&lt;/ul&gt;&lt;p&gt;$𝜆a.a (2)$ and apply the lambda to the number, thereby ending up with $2$&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Bound variables&lt;/dt&gt;&lt;dd&gt;Variables that are declared in the head of a function (y&apos;know, the &lt;i&gt;parameters&lt;/i&gt;)&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Codomain&lt;/dt&gt;&lt;dd&gt;The set of possible outputs of a function.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Combinators&lt;/dt&gt;&lt;dd&gt;A lambda term with &lt;i&gt;no free variables&lt;/i&gt;. In other words, all variables are in the head.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Divergence&lt;/dt&gt;&lt;dd&gt;Any function that never terminates is &lt;i&gt;divergent&lt;/i&gt; (hint: recursive functions that never exit, loops of the &lt;code&gt;while(true)&lt;/code&gt; type).&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Domain&lt;/dt&gt;&lt;dd&gt;The set of possible inputs to a function.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Free variables&lt;/dt&gt;&lt;dd&gt;Variables that exist in a function body that are not defined in the head, such as the $y$ in this expression:&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;$𝜆x.xy$&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Lambda&lt;/dt&gt;&lt;dd&gt;The Greek letter 𝜆. Used to indicate abstractions (functions) and bind variables.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Lambda abstraction&lt;/dt&gt;&lt;dd&gt;An anonymous function or lambda term. You can think of the head as an abstraction for the body, i.e. something we can put in place of the computation.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Referential transparency (/aka/ purity)&lt;/dt&gt;&lt;dd&gt;This means that given the same input, a function will always produce the same output.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;p&gt;While this may seem a strange place to start, I can see the logic in doing it, and getting a better understanding of the lambda calculus is helpful anyway, so I&apos;m fine with starting it this way.&lt;/p&gt;&lt;p&gt;Anyway, there should be more code in the later chapters. Until next time!&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Command Line Control: awk]]></title><description><![CDATA[In which I learn a whole new language just to be able to kill applications with a single command. A basic introduction to the awk command and the AWK language that powers it; covering how it works, some language built-ins, and a few examples to get the creative juices flowing.]]></description><link>https://blog.thomasheartman.com/posts/command-line-control-awk</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/command-line-control-awk</guid><pubDate>Sat, 08 Jun 2019 15:19:18 GMT</pubDate><content:encoded>&lt;p&gt;Unless you spend a whole lot of time working primarily on the command line, &lt;code&gt;awk&lt;/code&gt; is one of those commands you&apos;ve likely come across a few times, but never really learned how to use properly. Similar to my recent adventures with &lt;code&gt;xargs&lt;/code&gt;, though, I recently came across a little use case where I could benefit from using it, so I decided to sit down and look into it.&lt;/p&gt;&lt;p&gt;Even more so than with &lt;code&gt;xargs&lt;/code&gt;, this is a &lt;i&gt;really&lt;/i&gt; powerful tool, but let&apos;s focus on the basics and see what we can make of it.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;What is &lt;code&gt;awk&lt;/code&gt;?&lt;/h2&gt;&lt;p&gt;&lt;code&gt;awk&lt;/code&gt; is a command that processes text using programs written in the AWK language.&lt;/p&gt;&lt;p&gt;To understand what it can do, understanding the language it uses is probably a good place to start. Let&apos;s use the words of Alfred Aho---one of the creators of the &lt;i&gt;AWK&lt;/i&gt; language---from a &lt;a href=&quot;https://web.archive.org/web/20080808234125/http://www.computerworld.com.au/index.php/id%3B1726534212%3Bpp%3B2&quot;&gt;2008 /Computerworld/ interview&lt;/a&gt; to get a rough grasp of what it is:&lt;/p&gt;&lt;blockquote&gt;AWK is a language for processing files of text. A file is treated as a sequence of records, and by default each line is a record. Each line is broken up into a sequence of fields, so we can think of the first word in a line as the first field, the second word as the second field, and so on. An AWK program is of a sequence of pattern-action statements. AWK reads the input a line at a time. A line is scanned for each pattern in the program, and for each pattern that matches, the associated action is executed.&lt;/blockquote&gt;&lt;p&gt;That may be a bit dense, so let&apos;s take it apart:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;&quot;AWK is a language for processing [..] text&quot;&lt;/dt&gt;&lt;dd&gt;AWK is a &lt;i&gt;domain-specific language&lt;/i&gt; (DSL) focused on text processing. The &lt;code&gt;awk&lt;/code&gt; command expects that its first argument is a script or a string in this language.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;&quot;AWK reads the input a line at a time&quot;&lt;/dt&gt;&lt;dd&gt;AWK is line-oriented and works through the input line by line. (It&apos;s actually &lt;i&gt;record&lt;/i&gt;-oriented, but the default separator is a newline character, so this is the same thing by default.)&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;&quot;Each line is broken into a sequence of fields&quot;&lt;/dt&gt;&lt;dd&gt;Each word in a line maps to a field. These fields are accessed with the &lt;code&gt;$&lt;/code&gt; operator, e.g. &lt;code&gt;$1&lt;/code&gt; for the first word, &lt;code&gt;$2&lt;/code&gt; for the second, and so on. &lt;code&gt;$0&lt;/code&gt; is the whole line. By default, fields are delimited by whitespace (which is why I&apos;ve called them words) but this can be customized.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;&quot;An AWK program is of a sequence of pattern-action statements&quot;&lt;/dt&gt;&lt;dd&gt;This means it&apos;s a sequence of predicates with actions. If a predicate evaluates to true, perform the specified action. If no predicate is specified, it will always evaluate to true, and if no action is specified, it will default to printing the whole line.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;&lt;i&gt;Huh?&lt;/i&gt; Yeah, this is still a bit confusing, but maybe some examples will make it clearer:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Patterns&lt;/dt&gt;&lt;dd&gt;This is a predicate to check each line against. It usually takes the form of a regex enclosed in forward slashes. &lt;code&gt;/foo/&lt;/code&gt;, &lt;code&gt;/b[ar]?/&lt;/code&gt;, &lt;code&gt;/^baz/&lt;/code&gt;, &lt;code&gt;/(fizz|buzz)$/&lt;/code&gt; are all examples. Most of the regex skills you have will be applicable here (character sets, character classes, alternations, etc.).&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;You can also match specific fields against a regex. Only want to match lines where the second field contains &apos;cheese&apos;? &lt;code&gt;$2 ~ /cheese/&lt;/code&gt;&lt;/p&gt;&lt;p&gt;The pattern can also consist of functions and comparisons; so if you wish to act only on lines that aren&apos;t empty: &lt;code&gt;length &gt; 0&lt;/code&gt;&lt;/p&gt;&lt;p&gt;If no pattern is given, every line will match.&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Actions&lt;/dt&gt;&lt;dd&gt;These are commands telling &lt;code&gt;awk&lt;/code&gt; what to execute. They are enclosed in curly braces (&lt;code&gt;{}&lt;/code&gt;). This is where you might instruct &lt;code&gt;awk&lt;/code&gt; to print a certain field of the string---~print $3~, for instance---or increment a counter if you&apos;re counting words: &lt;code&gt;word_count += NF&lt;/code&gt; (yeah, I&apos;ll get to what &lt;code&gt;NF&lt;/code&gt; means in a bit).&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;If no action is given, &lt;code&gt;awk&lt;/code&gt; will print the matching line.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Basic &lt;del&gt;auth&lt;/del&gt; &lt;code&gt;awk&lt;/code&gt;&lt;/h2&gt;&lt;p&gt;That&apos;s a quick overview of how the language is structured. Before we start playing with it, let&apos;s explore some of the features.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Built-in variables&lt;/h3&gt;&lt;p&gt;&lt;code&gt;awk&lt;/code&gt; has a number built-in variables, and while I won&apos;t cover all of them, these are the ones that I&apos;ve found the most useful:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;~NR~&lt;/dt&gt;&lt;dd&gt;Gives you the line number of the current match. Could be used for adding line numbers to an input file: ~awk &apos;{print NR, $0}&apos;~. Or maybe looking for lines that contain &apos;ice cream&apos; is more your speed: ~awk &apos;&lt;i&gt;ice cream&lt;/i&gt; {print NR}&apos;~.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;~NF~&lt;/dt&gt;&lt;dd&gt;This is the number of fields in a line. Useful if you&apos;re looking for the last field, either for finding out how many fields are in a line or for seeing if it contains a pattern: &lt;code&gt;awk &apos;$NF ~ /out/ {print NR}&lt;/code&gt;&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;~FS~&lt;/dt&gt;&lt;dd&gt;The field separator value. This is what &lt;code&gt;awk&lt;/code&gt; will use to split each line into fields. By default this is whitespace. If you have a file full of comma-separated values and want to split each line on commas instead of whitespace: &lt;code&gt;BEGIN {FS=&quot;,&quot;}&lt;/code&gt;&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;~RS~&lt;/dt&gt;&lt;dd&gt;This is the line (&apos;record&apos;) equivalent of the field separator. The default is &lt;code&gt;\n&lt;/code&gt;. Say you want to print your &lt;code&gt;PATH&lt;/code&gt; over multiple lines: ~echo $PATH | awk &apos;BEGIN {RS=&quot;:&quot;} {print}&apos;~&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;&lt;code&gt;BEGIN&lt;/code&gt; and &lt;code&gt;END&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;&lt;code&gt;awk&lt;/code&gt; lets you supply commands to be executed at the start and end of a script by using  &lt;code&gt;BEGIN&lt;/code&gt; and &lt;code&gt;END&lt;/code&gt;. While they may seem like it, they&apos;re not really special at all. Instead, think of them as being patterns that evaluate to true before &lt;i&gt;anything&lt;/i&gt; is evaluated and after &lt;i&gt;everything&lt;/i&gt; is evaluated, respectively.&lt;/p&gt;&lt;p&gt;&lt;code&gt;BEGIN&lt;/code&gt; could be used to set the field separator or initialize a variable.&lt;/p&gt;&lt;p&gt;&lt;code&gt;END&lt;/code&gt; is useful for printing out results accrued through the life of the program, such as a word count. If we bring back our word counting example: ~awk &apos;{word_count += NF} END {print word_count}&apos;~&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Functions and conditionals&lt;/h3&gt;&lt;p&gt;Like most languages, AWK has a number of built-in functions (such as the &lt;code&gt;print&lt;/code&gt; and &lt;code&gt;length&lt;/code&gt; functions we saw earlier) and also lets you define your own functions if you so please. This is probably overkill for most trivial operations but could come in handy in certain cases.&lt;/p&gt;&lt;p&gt;And AWK has conditionals too! While you can use the &lt;code&gt;if else&lt;/code&gt; construct within actions, I&apos;d like to highlight that you can do conditional statements based on the supplied pattern. I.e. &lt;code&gt;awk &apos;/foo/ {print &quot;FOO&quot;} {print &quot;bar&quot;}&apos;~ will print &apos;FOO&apos; for lines that match ~/foo/&lt;/code&gt; and &apos;bar&apos; for lines that don&apos;t.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Applications&lt;/h2&gt;&lt;p&gt;Now that we&apos;ve got some idea how it works, what can we use it for? Let&apos;s look at some sample applications for it:&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Sorting lines in a file by length&lt;/h3&gt;&lt;p&gt;Here&apos;s a fun little application: Let&apos;s take a file, count the number of characters in each line, and then sort it based on the number of characters:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;awk &lt;span class=&quot;hljs-string&quot;&gt;&apos;{print length, $0}&apos;&lt;/span&gt; &amp;#x3C;file&gt; | sort -n&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And if you want to exclude empty lines, try this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;awk &lt;span class=&quot;hljs-string&quot;&gt;&apos;length &gt; 0 {print length, $0}&apos;&lt;/span&gt; &amp;#x3C;file&gt; | sort -n&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Friendly &lt;code&gt;PATH&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;This is the same one that was listed above, and is useful if you&apos;re looking for certain entries that can easily get lost when the path is on one line:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# bash, zsh&lt;/span&gt;
&lt;span class=&quot;hljs-built_in&quot;&gt;echo&lt;/span&gt; &lt;span class=&quot;hljs-variable&quot;&gt;$PATH&lt;/span&gt; | awk &lt;span class=&quot;hljs-string&quot;&gt;&apos;BEGIN {RS=&quot;:&quot;} {print}&apos;&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;# fish&lt;/span&gt;
&lt;span class=&quot;hljs-built_in&quot;&gt;echo&lt;/span&gt; &lt;span class=&quot;hljs-variable&quot;&gt;$PATH&lt;/span&gt; | awk &lt;span class=&quot;hljs-string&quot;&gt;&apos;BEGIN {RS=&quot; &quot;} {print}&apos;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Counting words&lt;/h3&gt;&lt;p&gt;Another example that was used previously. Count the words in a file or any input stream:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;awk &lt;span class=&quot;hljs-string&quot;&gt;&apos;{word_count += NF} END {print word_count}&apos;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Parsing git logs&lt;/h3&gt;&lt;p&gt;Maybe your team has agreed that all commit messages should start with &lt;code&gt;#&amp;#x3C;task_no&gt;&lt;/code&gt; if it relates to a task and &lt;code&gt;#--&lt;/code&gt; if it doesn&apos;t. To find all commits that relate to a specific task---say &lt;code&gt;#42&lt;/code&gt;---we could do this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git &lt;span class=&quot;hljs-built_in&quot;&gt;log&lt;/span&gt; --oneline | awk &lt;span class=&quot;hljs-string&quot;&gt;&apos;/#42/ {print $1}&apos;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Or how about finding the ratio of commits that belong to a task versus those that don&apos;t?&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git &lt;span class=&quot;hljs-built_in&quot;&gt;log&lt;/span&gt; --oneline --no-decorate | \
awk &lt;span class=&quot;hljs-string&quot;&gt;&apos;$2 ~ /#[0-9]+/ {task += 1} {notask +=1} \
  END {printf &quot;Tasks: %d\nNo-tasks: %d\nTask to no-task ratio: %f&quot;, \
  task, notask, task / notask }&apos;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;(Yeah, the &lt;code&gt;printf&lt;/code&gt; function works pretty much the same as in C---so much so that I haven&apos;t looked it up yet!)&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Killing processes&lt;/h3&gt;&lt;p&gt;This is actually what triggered me to look into &lt;code&gt;awk&lt;/code&gt; and what eventually led to this post being brought into existence.&lt;/p&gt;&lt;p&gt;There are a number of ways to kill applications from the command line, and for a while, my default fallback has been the classic &lt;code&gt;ps aux | grep &amp;#x3C;app&gt;&lt;/code&gt; combo.&lt;/p&gt;&lt;p&gt;While this lists out all the relevant processes and their process IDs (&lt;i&gt;PIDs&lt;/i&gt;), you then have to manually copy the PID and put it into the &lt;code&gt;kill&lt;/code&gt; command to shut it down. This is annoying at best, and gets even worse if the process has spawned children that we want to take down as well.&lt;/p&gt;&lt;p&gt;How do we deal with this? Well:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;ps aux | awk &lt;span class=&quot;hljs-string&quot;&gt;&apos;/&amp;#x3C;app&gt;/ {print $2}&apos;&lt;/span&gt; | xargs &lt;span class=&quot;hljs-built_in&quot;&gt;kill&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;ol&gt;&lt;li&gt;&lt;code&gt;ps&lt;/code&gt; lists all processes on the system&lt;/li&gt;&lt;/ol&gt;&lt;ol&gt;&lt;li&gt;&lt;code&gt;awk&lt;/code&gt; then goes over every line that contains the application name, extracts the second whitespace-delimited word---which in this case is the PID---and prints that.&lt;/li&gt;&lt;/ol&gt;&lt;ol&gt;&lt;li&gt;For the last stretch, we use &lt;code&gt;xargs&lt;/code&gt; to feed the PIDs into the &lt;code&gt;kill&lt;/code&gt; command, thus killing all the processes.&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;This works just fine, though it comes with the caveat that it&apos;ll also try and kill the &lt;code&gt;awk&lt;/code&gt; process (because the application name is part of the command, so it gets listed by &lt;code&gt;ps&lt;/code&gt;), but that&apos;s only a minor annoyance, and I&apos;ll leave fixing that as an exercise for the reader.&lt;/p&gt;&lt;p&gt;Now, I&apos;m sure you can make &lt;code&gt;killall&lt;/code&gt; do something quite similar to this, but I&apos;ve found this way to be more effective (by which I mean: &lt;i&gt;closer to what I expect&lt;/i&gt;).&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Closing up&lt;/h2&gt;&lt;p&gt;&lt;i&gt;Phew&lt;/i&gt;. We&apos;ve learned a lot today, and this post grew much longer than what I had originally imagined---about four or five times longer---but it&apos;s been quite the journey and I&apos;m glad you were there with me, partner. I hope you&apos;ve gleaned some new insight too and that you&apos;ll find some application for this in your day-to-day.&lt;/p&gt;&lt;p&gt;See you next time!&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Hakyll CI builds in one fifth of the time]]></title><description><![CDATA[In which I finally manage to bring the deployment time of this site under control. We look at how Stack and Nix interact, what consequences having a completely isolated build environment might have, and how you might work around issues that arise from this.]]></description><link>https://blog.thomasheartman.com/posts/hakyll-ci-builds-in-one-fifth-of-the-time</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/hakyll-ci-builds-in-one-fifth-of-the-time</guid><pubDate>Sun, 02 Jun 2019 10:50:37 GMT</pubDate><content:encoded>&lt;p&gt;As I&apos;ve mentioned before, one of the big pain points relating to this blogging business is deployment time: Haskell is slow to compile and &lt;i&gt;Hakyll&lt;/i&gt; has multiple large dependencies, so the builds would initially take up to an hour. Yeah, you read that right. &lt;i&gt;60 minutes&lt;/i&gt; 😱. Something goes wrong towards the end of the build? Sucks to be you.&lt;/p&gt;&lt;p&gt;Thanks to &lt;a href=&quot;https://sakshamsharma.com&quot;&gt;Saksham Sharma&lt;/a&gt; and their &lt;a href=&quot;https://sakshamsharma.com/2018/03/docker-hakyll-builds/&quot;&gt;post on speeding up Haskell CI builds&lt;/a&gt;, however, I have been able to bring it down to 7-8 minutes in GitLab&apos;s CI/CD systems (excluding time spent waiting for runners to spin up etc.). That said, it wasn&apos;t quite as easy as I&apos;d hoped it would be (when is it ever?): Due to how &lt;i&gt;Stack&lt;/i&gt; and &lt;i&gt;Nix&lt;/i&gt; interact, building of the site would crash when it ran into UTF-8-encoded characters. &lt;i&gt;Not cool.&lt;/i&gt;&lt;/p&gt;&lt;p&gt;Let&apos;s fix it.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Step 1: using an image with Hakyll pre-built&lt;/h2&gt;&lt;p&gt;In Sharma&apos;s post, they mention that they&apos;ve created an image that you can use for your build systems. The simplest version would look a little something like this (freely updated from their &lt;a href=&quot;https://sakshamsharma.com/2018/03/docker-hakyll-builds/&quot;&gt;minimal configuration example&lt;/a&gt;):&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-yaml&quot;&gt;&lt;span class=&quot;hljs-attr&quot;&gt;image:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;sakshamsharma/docker-hakyll:v3&lt;/span&gt;

&lt;span class=&quot;hljs-attr&quot;&gt;pages:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;script:&lt;/span&gt;
    &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;stack&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;build&lt;/span&gt;
    &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;stack&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;exec&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;site&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;build&lt;/span&gt;
  &lt;span class=&quot;hljs-comment&quot;&gt;# ... rest of stage omitted&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;An important thing to note is that your stack config&apos;s resolver must match the one used in the Docker image, otherwise the build system would have to recompile Hakyll and its dependencies for your version, taking us back to the hour-long builds.&lt;/p&gt;&lt;p&gt;For &lt;code&gt;v3&lt;/code&gt;, the resolver is &lt;code&gt;lts-12.21&lt;/code&gt;, so make sure your project&apos;s &lt;code&gt;stack.yaml&lt;/code&gt; contains the following line:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-yaml&quot;&gt;&lt;span class=&quot;hljs-attr&quot;&gt;resolver:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;lts-12.21&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If this works for you and is all you need: &lt;i&gt;great&lt;/i&gt;! If it doesn&apos;t and you get errors talking about invalid byte sequences like the one below: don&apos;t panic. I&apos;ll sort you out.&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;Compiling
  [ERROR] ./about.rst: hGetContents: invalid argument (invalid byte sequence)&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Step 2: This one weird trick&lt;/h2&gt;&lt;pre class=&quot;aside&quot;&gt;As described in [[https://github.com/commercialhaskell/stack/issues/2358#issuecomment-466818624][this GitHub issue]], a fix for the above error is available in Stack&apos;s master branch and as of Stack v2.1---the release candidate for which was released while I was writing this post---will be included with the tool.

From the [[https://github.com/commercialhaskell/stack/releases/tag/v2.1.0.1][release notes for the release candidate]]: &quot;Use en_US.UTF-8 locale by default in pure Nix mode so programs won&apos;t crash because of Unicode in their output&quot;.

So if you&apos;re using Stack v2.1 or later, the steps outlined in this section should not be necessary.&lt;/pre&gt;&lt;p&gt;As evidenced by a fair few GitHub issues&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;, this is something that a number of users run into and it might be difficult to troubleshoot, but what it boils down to is this: When running Stack in Nix mode it defaults to building in pure mode. This isolates the build environment by removing environment variables and other things on your system that could influence the build and lead to a lack of reproducibility. This is usually a good thing, but it also unsets the &lt;code&gt;LANG&lt;/code&gt; variable, which Stack relies on to know how it should handle encodings.&lt;/p&gt;&lt;p&gt;&lt;i&gt;Ok. So all we gotta do is re-set that variable, then?&lt;/i&gt; Yes. But how to do that might not be immediately apparent. You might be used to running shell commands like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;MY_VAR=&lt;span class=&quot;hljs-string&quot;&gt;&quot;my-value&quot;&lt;/span&gt; ls -lah&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;But this won&apos;t work with Stack, because it&apos;ll still isolate the environment. What you can do, however, is to use the &lt;code&gt;--no-nix-pure&lt;/code&gt; option. This tells Stack not to isolate the build environment, so you&apos;ll still be able to access external variables. Here&apos;s an extract from my current build file that does just that:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-yaml&quot;&gt;&lt;span class=&quot;hljs-attr&quot;&gt;image:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;sakshamsharma/docker-hakyll:v3&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;script:&lt;/span&gt;
  &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;stack&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;build&lt;/span&gt;
  &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;stack&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;exec&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;--no-nix-pure&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;site&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;build&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This works perfectly on GitLab&apos;s CI runners, but if this still doesn&apos;t solve your issue, you might want to check what the locale is actually set to by using the &lt;code&gt;locale&lt;/code&gt; shell command. The output should look something like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;$ locale
LANG=en_US.UTF-8
LC_CTYPE=&lt;span class=&quot;hljs-string&quot;&gt;&quot;en_US.UTF-8&quot;&lt;/span&gt;
LC_NUMERIC=&lt;span class=&quot;hljs-string&quot;&gt;&quot;en_US.UTF-8&quot;&lt;/span&gt;
LC_TIME=&lt;span class=&quot;hljs-string&quot;&gt;&quot;en_US.UTF-8&quot;&lt;/span&gt;
LC_COLLATE=&lt;span class=&quot;hljs-string&quot;&gt;&quot;en_US.UTF-8&quot;&lt;/span&gt;
LC_MONETARY=&lt;span class=&quot;hljs-string&quot;&gt;&quot;en_US.UTF-8&quot;&lt;/span&gt;
LC_MESSAGES=&lt;span class=&quot;hljs-string&quot;&gt;&quot;en_US.UTF-8&quot;&lt;/span&gt;
LC_PAPER=&lt;span class=&quot;hljs-string&quot;&gt;&quot;en_US.UTF-8&quot;&lt;/span&gt;
LC_NAME=&lt;span class=&quot;hljs-string&quot;&gt;&quot;en_US.UTF-8&quot;&lt;/span&gt;
LC_ADDRESS=&lt;span class=&quot;hljs-string&quot;&gt;&quot;en_US.UTF-8&quot;&lt;/span&gt;
LC_TELEPHONE=&lt;span class=&quot;hljs-string&quot;&gt;&quot;en_US.UTF-8&quot;&lt;/span&gt;
LC_MEASUREMENT=&lt;span class=&quot;hljs-string&quot;&gt;&quot;en_US.UTF-8&quot;&lt;/span&gt;
LC_IDENTIFICATION=&lt;span class=&quot;hljs-string&quot;&gt;&quot;en_US.UTF-8&quot;&lt;/span&gt;
LC_ALL=&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If the output doesn&apos;t show a UTF-8 format, that seems like a good place to start (I&apos;d try &lt;code&gt;EXPORT LANG=en_US.UTF-8&lt;/code&gt; before running the Stack commands), but now we&apos;re wading out past the scope of this post, so you&apos;re gonna have to go it on your own, I&apos;m afraid. Sorry, kiddo.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Wrapping up&lt;/h2&gt;&lt;p&gt;And that&apos;s it! Simple, but not immediately obvious. It&apos;s likely that a similar approach---the prepared Nix container---would work for other Haskell projects as well, though I can&apos;t say for certain one way or the other.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;p&gt;&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt; A selection of GitHub issues relating to the unicode problem:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;https://github.com/jaspervdj/hakyll/issues/614&quot;&gt;hakyll can&apos;t handle unicode?&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://github.com/commercialhaskell/stack/issues/2358&quot;&gt;Enabling nix causes LANG to be lost.&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://github.com/commercialhaskell/stack/issues/793&quot;&gt;commitBuffer: invalid argument (invalid character)&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[xargs and the unruly tags]]></title><description><![CDATA[In which my CI/CD pipeline gets stuck in a recursive loop and I learn how to use xargs and how to delete remote git tags. If you've seen xargs in the wild, but never quite understood what it does: This one's for you!]]></description><link>https://blog.thomasheartman.com/posts/xargs-and-the-unruly-tags</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/xargs-and-the-unruly-tags</guid><pubDate>Sat, 25 May 2019 14:01:57 GMT</pubDate><content:encoded>&lt;p&gt;I thought I was really clever when I configured my CI/CD pipeline to tag commits that got deployed and push the tags back into the repo, but I&apos;m rarely as clever as I like to think: I had forgotten to put the proper checks in place to avoid these tag pushes triggering subsequent runs of the pipeline, and things got a little ... &lt;i&gt;out of hand&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;I&apos;d gone to bed just after pushing an update, and when I arose to check on it, I found that the deploy tagging stage had been running over and over and over and over and ... you get the point. Thankfully, it had failed after about 130 rounds, so it could have been a lot worse, but I &lt;i&gt;was&lt;/i&gt; left with a large amount of useless and unwanted tags in the remote repo.&lt;/p&gt;&lt;p&gt;So how do you fix something like this? Yup, &lt;code&gt;xargs&lt;/code&gt; to the rescue!&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Where there&apos;s a will ...&lt;/h2&gt;&lt;p&gt;At first, I didn&apos;t really know how I&apos;d go about it. I was hoping git would have some nice, built-in functionality for mass-deleting remote tags, but while I have found in retrospect that it does (see &lt;a href=&quot;postmortem&quot;&gt;the postmortem&lt;/a&gt;), I couldn&apos;t find it at the time.&lt;/p&gt;&lt;p&gt;However, because all the tags were for a specific commit, I &lt;i&gt;did&lt;/i&gt; know that I could list all the relevant tags separated by newlines, using &lt;code&gt;git tag --contains &amp;#x3C;SHA&gt;&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;So, with some helpful advice from Stack Overflow and &lt;a href=&quot;http://theknarf.com/&quot;&gt;this guy&lt;/a&gt;, I constructed this little command which sorted me out just fine:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git tag --contains 9216e97ce7e66090f79eba4d1abe6548d72dd638 \
| xargs -I % git push origin :refs/tags/%&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now, I&apos;d come across &lt;code&gt;xargs&lt;/code&gt; before, even done the ol&apos; copying and pasting from Stack Overflow trick, but it had always looked really complicated and no-one had ever told me why I&apos;d need it or what it does; so I just carried on in blissful ignorance. Not this time, though. It was time to figure out what was going on.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Groking &lt;code&gt;xargs&lt;/code&gt;&lt;/h2&gt;&lt;p&gt;The way &lt;code&gt;xargs&lt;/code&gt; was sold to me was: &quot;execute a command for each item in a list&quot;. It&apos;s actually more powerful than that, but that&apos;s a great place to start.&lt;/p&gt;&lt;p&gt;Let&apos;s use the &lt;code&gt;man&lt;/code&gt; page to find out what that &lt;code&gt;-I %&lt;/code&gt; bit means :&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;~-I~&lt;/dt&gt;&lt;dd&gt;&lt;strong&gt;replace-str&lt;/strong&gt;: &quot;Replace occurrences in the initial-arguments with names read from standard input&quot;&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;The string to use to indicate where to place arguments in the command to run. In the command above, we chose to use &lt;code&gt;%&lt;/code&gt;, but you&apos;re not limited to this.&lt;/p&gt;&lt;p&gt;Similar to &lt;code&gt;printf&lt;/code&gt; and format strings in general, this places your arguments at your desired place in the command. In our case it both limits us to using one argument (tag) at a time, and it lets us append it to &lt;code&gt;:refs/tags/&lt;/code&gt; without being separated by a space.&lt;/p&gt;&lt;p&gt;That means that in the above snippet, &lt;code&gt;xargs&lt;/code&gt; would, for each tag listed, run the command &lt;code&gt;git push origin :refs/tags/&amp;#x3C;tag_name&gt;&lt;/code&gt;, which pushes that tag with an empty reference, thereby deleting it.&lt;/p&gt;&lt;p&gt;If all you want is to put the argument at the end of the command, you can even do without the &lt;code&gt;-I&lt;/code&gt;. Say you want to recursively delete all the &lt;code&gt;.swp&lt;/code&gt; files in a directory:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;find -name &lt;span class=&quot;hljs-string&quot;&gt;&quot;*.swp&quot;&lt;/span&gt; | xargs rm&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Be aware, though, that without either using a &lt;code&gt;-I&lt;/code&gt; or &lt;code&gt;-n&lt;/code&gt; (to limit the number of arguments to use for each command), &lt;code&gt;xargs&lt;/code&gt; will split the list you give it into sizeable chunks and apply as many arguments to the command as it can each time. That means that in this case, it&apos;d likely end up looking something like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;rm a.swp b.swp c.swp ...&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;which is usually fine and what you want, but keep this in mind for when it isn&apos;t.&lt;/p&gt;&lt;p&gt;This is only scratching the surface of what &lt;code&gt;xargs&lt;/code&gt; can do, but it&apos;s enough to make it do some pretty heavy lifting. It might not be something to reach for very often, but for when you do need it, it&apos;s a great tool to have in your belt.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Postmortem ⚰️&lt;/h2&gt;&lt;p&gt;&amp;#x3C;&amp;#x3C;postmortem&gt;&gt; Now, you might have noticed that I did a &lt;code&gt;git push&lt;/code&gt; for each tag that I was deleting, and you might be thinking that for over a hundred tags, it must have taken quite some time. You would be right. Luckily, I was working on something else, so I could happily let it run in the background. But we can do better!&lt;/p&gt;&lt;p&gt;&lt;code&gt;xargs&lt;/code&gt; has an option &lt;code&gt;-P&lt;/code&gt; or &lt;code&gt;--max-procs&lt;/code&gt;, which you can use to decide how many processes to run in parallel. The default is 1, but if you set it to 0, it will run as many as it can. This could have saved us quite some time, assuming git would let us run multiple &lt;code&gt;push&lt;/code&gt; operations from the same repo at the same time. But there is an even better way:&lt;/p&gt;&lt;p&gt;As outlined in &lt;a href=&quot;https://stackoverflow.com/a/12791414&quot;&gt;this Stack Overflow response&lt;/a&gt;, you can use a whitespace-separated list of tag names (&lt;code&gt;&amp;#x3C;tags&gt;&lt;/code&gt;) with &lt;code&gt;git push~; so we could have run ~git push --delete origin &amp;#x3C;tags&gt;&lt;/code&gt; to achieve the same outcome as deleting them one by one.&lt;/p&gt;&lt;p&gt;If we rewrite the command from earlier, we can both simplify it &lt;i&gt;and&lt;/i&gt; do it all in a single push:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;git tag --contains 9216e97ce7e66090f79eba4d1abe6548d72dd638 \
| xargs git push --delete origin&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;... yeah, that would have been a lot more efficient 😅&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Docking pains]]></title><description><![CDATA[In which I install Docker, fumble with user groups, realize my root partition is running out of space, and spend far too much time on something I expected to be a simple matter.]]></description><link>https://blog.thomasheartman.com/posts/docking-pains</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/docking-pains</guid><pubDate>Sat, 18 May 2019 15:53:10 GMT</pubDate><content:encoded>&lt;p&gt;You know how some things are a lot more difficult than they seem? In an attempt to speed up deployments for this blog, I wanted to look into building a Docker image with &lt;i&gt;Hakyll&lt;/i&gt; and all the required build dependencies available. To be able to do this effectively, I figured I&apos;d need to have the ability to work with Docker locally. Turns out this was one of those things.&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;The goal&lt;/dt&gt;&lt;dd&gt;Enable Docker virtualisation and development on a NixOS system&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Challenges&lt;/dt&gt;&lt;dd&gt;The root partition---which is where Docker stores data---keeps running out of space&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;p&gt;In theory, it&apos;s simple:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;enable Docker&lt;/li&gt;&lt;li&gt;configure it to store data somewhere that is not &lt;code&gt;/var/lib/docker&lt;/code&gt;&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;In practice, it turns out to be a bit more difficult than expected, but don&apos;t worry: We&apos;ll figure it out together!&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Enabling&lt;/h2&gt;&lt;p&gt;According to the &lt;a href=&quot;https://nixos.org/nixos/manual/options.html#opt-virtualisation.docker.enable&quot;&gt;NixOS manual&lt;/a&gt; and the &lt;a href=&quot;https://nixos.wiki/wiki/Docker&quot;&gt;the Wiki article on Docker&lt;/a&gt; there&apos;s really not much to it: To enable Docker, all you need to do is update your &lt;code&gt;configuration.nix&lt;/code&gt; to include&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-nix&quot;&gt;virtualisation.docker.&lt;span class=&quot;hljs-attr&quot;&gt;enable&lt;/span&gt; = &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As pure and simple as Nix should be.&lt;/p&gt;&lt;p&gt;According to the manual: &quot;/This option enables docker, a daemon that manages linux containers. Users in the &quot;docker&quot; group can interact with the daemon (e.g. to start or stop containers) using the docker command line tool./&quot;&lt;/p&gt;&lt;p&gt;Read that last line carefully: &quot;/Users in the &quot;docker&quot; group can interact with the daemon [...]/&quot;. Yup. That means we need to make sure our user is in the correct group:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-nix&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# replace thomas with the name of your user&lt;/span&gt;
users.extraUsers.&lt;span class=&quot;hljs-attr&quot;&gt;thomas&lt;/span&gt; = {
  &lt;span class=&quot;hljs-attr&quot;&gt;extraGroups&lt;/span&gt; = [
    &lt;span class=&quot;hljs-string&quot;&gt;&quot;docker&quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;# ... other groups&lt;/span&gt;
  ];
&lt;span class=&quot;hljs-comment&quot;&gt;# ... remaining configuration&lt;/span&gt;
};&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;What isn&apos;t immediately obvious is this: You must log out and back in before this setting change takes effect. Let&apos;s repeat that to make sure we understand:&lt;/p&gt;&lt;p&gt;&lt;i&gt;You *must* log out and back in before this setting change takes effect.&lt;/i&gt;&lt;/p&gt;&lt;p&gt;From what I can tell, this goes for any change to a user&apos;s groups, but it isn&apos;t particularly well documented anywhere. (&lt;i&gt;Psst&lt;/i&gt;: I am &lt;a href=&quot;https://github.com/NixOS/nixpkgs/issues/6616#issuecomment-77743224&quot;&gt;not the only one&lt;/a&gt; to have run into this.)&lt;/p&gt;&lt;p&gt;But wait; there&apos;s more! This is only vaguely referenced in the manual (&quot;/using the docker command line tool/&quot;), but to have access to the Docker CLI, you&apos;re going to have to install Docker (&lt;code&gt;pkgs.docker&lt;/code&gt;) for your user, either by putting it in &lt;code&gt;configuration.nix&lt;/code&gt;&apos;s &lt;code&gt;systemPackages&lt;/code&gt; or by using a solution &lt;a href=&quot;https://gist.github.com/lheckemann/402e61e8e53f136f239ecd8c17ab1deb&quot;&gt;such as this&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;And that&apos;s it. If all you wanted to do was set up docker to run with the default configuration, you&apos;re done now. Congrats! Have a donut. You&apos;ve earned it.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;The space race&lt;/h2&gt;&lt;p&gt;Ah, yes, disk space ... We&apos;ve got Docker in place now, and, assuming the group change setting has taken effect, we can start playing with it. That&apos;s what I did. For a day or so. As per the usual NixOS song and dance, I wanted to change some configuration settings, so I tried to rebuild my system and got this fateful message:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sh&quot;&gt;No space left on device&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now, this isn&apos;t anything new. I&apos;ve realized since setting up the OS, that I should have probably allocated more space for the root partition (someone once told me that NixOS &quot;trades disk space for sanity&quot;). &quot;Oh, well,&quot; I thought. &quot;Guess I have to delete some old generations again.&quot; So I ran the garbage collector. This usually frees up about 7--10GB of space, but now it was hardly removing two! I tried all the tricks that I knew of, but nothing seemed to make a difference. And then the thought struck me: &quot;Docker is installed as a system service. That means it probably stores images system-wide too!&quot;. And indeed, after looking through the &apos;docks&apos; (&lt;i&gt;har har&lt;/i&gt;), I found that the default place Docker stores data is in &lt;code&gt;/var/lib/docker&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;So I killed all of my containers, deleted all of my images, and lo and behold: My root partition had suddenly lost nearly 10GB! Superb!&lt;/p&gt;&lt;p&gt;The next step, then, would be to figure out how to store the data somewhere else. Luckily, the docs (NixOS and Docker) are quite clear on this point: For your Docker configuration, you can specify an option, &lt;code&gt;--data-root&lt;/code&gt;, and have the data stored there instead. In general, I prefer not to mess around with where things are stored too much, but in some cases it makes life easier (until I get around to repartitioning my drive, anyway), so I decided I&apos;d put it under &lt;code&gt;/home/docker&lt;/code&gt; for now. This is easily done like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-nix&quot;&gt;virtualisation.docker.&lt;span class=&quot;hljs-attr&quot;&gt;extraOptions&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;--data-root /home/docker&quot;&lt;/span&gt;;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This setting means that my &lt;code&gt;/home&lt;/code&gt; partition carries some extra data, but it&apos;s got more than enough space to deal with it.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Putting it into practice&lt;/h2&gt;&lt;p&gt;Now, having experienced first-hand how space-hungry Docker can be, and having read through the documentation, I found that there are other options that might come in handy. For now, I decided to have the system aggressively auto-prune on a weekly basis. This should keep me from running into space issues any time soon, and if it gets annoying I can always change the settings.&lt;/p&gt;&lt;p&gt;At the end of this little adventure, the resulting &lt;code&gt;configuration.nix&lt;/code&gt; should look something like this:&lt;/p&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-nix&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# Docker CLI (either put this here or in your user config)&lt;/span&gt;
environment.&lt;span class=&quot;hljs-attr&quot;&gt;systemPackages&lt;/span&gt; = &lt;span class=&quot;hljs-keyword&quot;&gt;with&lt;/span&gt; pkgs; [ docker ];

&lt;span class=&quot;hljs-comment&quot;&gt;# Put your user in the correct group&lt;/span&gt;
users.extraUsers.thomas.&lt;span class=&quot;hljs-attr&quot;&gt;extraGroups&lt;/span&gt; = [ &lt;span class=&quot;hljs-string&quot;&gt;&quot;docker&quot;&lt;/span&gt; ];

&lt;span class=&quot;hljs-comment&quot;&gt;# Set up the Docker daemon&lt;/span&gt;
virtualisation.&lt;span class=&quot;hljs-attr&quot;&gt;docker&lt;/span&gt; = {
  &lt;span class=&quot;hljs-attr&quot;&gt;enable&lt;/span&gt; = &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;;
  &lt;span class=&quot;hljs-attr&quot;&gt;autoPrune&lt;/span&gt; = {
    &lt;span class=&quot;hljs-attr&quot;&gt;enable&lt;/span&gt; = &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;;
    &lt;span class=&quot;hljs-attr&quot;&gt;flags&lt;/span&gt; = [&lt;span class=&quot;hljs-string&quot;&gt;&quot;--all&quot;&lt;/span&gt;];
  };
  &lt;span class=&quot;hljs-attr&quot;&gt;extraOptions&lt;/span&gt; = &lt;span class=&quot;hljs-string&quot;&gt;&quot;--data-root /home/docker&quot;&lt;/span&gt;;
};&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In summary, these are the steps needed:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Enable &lt;code&gt;virtualisation.docker&lt;/code&gt;&lt;/li&gt;&lt;li&gt;Make sure your user is in the ~&quot;docker&quot;~ group. (&lt;i&gt;Log out and back in!&lt;/i&gt;)&lt;/li&gt;&lt;li&gt;Install Docker for your user&lt;/li&gt;&lt;li&gt;(Optional) If, like me, you have issues with space, change the &lt;code&gt;data-root&lt;/code&gt; to somewhere else, such as a different partition or an external drive.&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;So there you have it, folks! It really is quite simple ... once you figure out all the tricky parts.&lt;/p&gt;&lt;/div&gt;</content:encoded></item><item><title><![CDATA[Hello, World!]]></title><description><![CDATA[In which I introduce my new blog to the world and give a brief overview of what goes into making it, including configuring Hakyll, Netlify, and GitLab to do my bidding and writing little Python scripts to automate the timestamp process.]]></description><link>https://blog.thomasheartman.com/posts/hello-world</link><guid isPermaLink="false">https://blog.thomasheartman.com/posts/hello-world</guid><pubDate>Tue, 07 May 2019 04:14:30 GMT</pubDate><content:encoded>&lt;p&gt;As a first little post and an introduction to the blog, I thought it might be cute to have a little overview of how it&apos;s made. This has been my first time setting up most of the surrounding architecture and I have learned more than a few things in the process (though there is, of course, lots left to learn). This post won&apos;t go into great detail about any particular points, but will serve as more of an overview of what &apos;the system&apos; looks like at the time of writing.&lt;/p&gt;&lt;p&gt;That is to say: don&apos;t expect any brilliant insights from this post, but read on if you&apos;re interested in how I&apos;ve organized things.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Hakyll&lt;/h2&gt;&lt;p&gt;Let&apos;s start with the most important part of this whole thing, shall we? The truth is that without &lt;i&gt;[[https://jaspervdj.be/hakyll/][Hakyll]]&lt;/i&gt;, this blog would not be up and running now. I &lt;i&gt;have&lt;/i&gt; been wanting to get into writing for a bit, but I have been lacking a platform that met my criteria:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;I wanted to be able to write my posts using Emacs&apos; &lt;i&gt;[[https://orgmode.org/][Org mode]]&lt;/i&gt;&lt;/li&gt;&lt;li&gt;I wanted to be able to put them in a version controlled repo and have the blog auto-update whenever I pushed a new update.&lt;/li&gt;&lt;li&gt;I wanted it to be low-ish effort---at the very least I didn&apos;t want to mess with servers and so on---but I also wanted to be able to host it myself, so that I would not be dependent on some other platform.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Maybe I didn&apos;t look hard enough, but I couldn&apos;t really find any alternatives that would let me tick all these boxes. The closest was GitHub pages, which would have been fine, except that I would have had to restrict myself to markdown. ... but then a friend of mine told me about Hakyll and I found &lt;a href=&quot;https://turbomack.github.io/posts/2016-12-21-org-mode-in-hakyll.html&quot;&gt;this blog post&lt;/a&gt; on using it with Org mode. That was all I needed to set out.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Notable changes and additions&lt;/h3&gt;&lt;p&gt;While Hakyll comes with a lot of great features out of the box, I found that I wanted just a little bit more out of it, and these things had to be configured:&lt;/p&gt;&lt;dl&gt;&lt;div&gt;&lt;dt&gt;Feeds (RSS and atom)&lt;/dt&gt;&lt;dd&gt;I&apos;ve never used an RSS reader before, but in setting up this project I wanted to find out how the format works and ended up getting addicted myself. If you&apos;ve not tried it out: you might never wanna go back. Overall, this was quite easy, though it did require some tricksy loading of posts and applying different url treatment.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Sitemap&lt;/dt&gt;&lt;dd&gt;Another thing I&apos;ve never looked twice at. This project provided me a reason to understand what it is, why you might want it, and how you could set it up. Oh, and how you&apos;d link it in your &lt;code&gt;robots.txt&lt;/code&gt;. Pretty simple.&lt;/dd&gt;&lt;/div&gt;&lt;div&gt;&lt;dt&gt;Pagination&lt;/dt&gt;&lt;dd&gt;For some reason, it was quite important for me to be able to have a paginated stream of all blog posts (yup, that&apos;s &lt;a href=&quot;https://blog.thomasheartman.com/blog&quot;&gt;the blog page&lt;/a&gt;). Luckily, it was fairly easy to set up, though it did require me to change how I store post drafts.&lt;/dd&gt;&lt;/div&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Where I want to go&lt;/h3&gt;&lt;p&gt;I think I&apos;ve got it mostly where I want it now, but I&apos;m still not happy with how I store drafts. At the moment, they&apos;re in a &lt;code&gt;drafts&lt;/code&gt; directory under the &lt;code&gt;posts&lt;/code&gt; directory. In an ideal world I&apos;d be able to store them along with all other posts with the only way to tell whether they&apos;ve been published or not is whether they have a &lt;code&gt;published&lt;/code&gt; tag in their metadata. However, this causes some issues with Hakyll&apos;s build process when it tries to process unpublished posts for different parts of the site. It should be as simple as loading the correct snapshot based on a filtered group of posts, but I haven&apos;t quite gotten around to that yet.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Netlify&lt;/h2&gt;&lt;p&gt;Overall I&apos;ve been very happy with what Netlify has offered me thus far. Their documentation is great, their CLI tool is pretty nice, and they seem to have their stuff together.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;External domain providers&lt;/h3&gt;&lt;p&gt;Stupidly, I bought the domain from a different domain provider and then went to Netlify later. If I&apos;d had the foresight to check with Netlify first, I wouldn&apos;t have had to deal with setting up name servers and so on. It hasn&apos;t been that big a deal, and at least now I know you &lt;i&gt;can&lt;/i&gt;, but it would just have been easier if I&apos;d gone all in on Netlify, I think. Maybe next time.&lt;/p&gt;&lt;p&gt;It might be worth pointing out that by changing DNS records to have it all managed by Netlify, I got &lt;code&gt;https&lt;/code&gt; support for &apos;free&apos; (when the option would have been to pay for it, had I stayed with my domain provider).&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Haskell support (or lack thereof)&lt;/h3&gt;&lt;p&gt;However, even though Netlify does offer a pretty solid service, their CI/CD system does not, at the time of writing, offer Haskell support&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;. This means that for now, I&apos;m stuck using an external service to build and then publish to their systems. While this isn&apos;t too bad, it does mean that I miss out on certain benefits that using their integrated system gives you, including minification and dynamic image serving.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;GitLab&lt;/h2&gt;&lt;p&gt;As Netlify doesn&apos;t support Haskell static site generators out of the box, I have to work around them and use an external CI/CD system instead. This is actually a big part of the reason why I chose GitLab for hosting this site: I&apos;ve used their systems a fair bit lately and find them rather nice to work with.&lt;/p&gt;&lt;p&gt;For my CI/CD setup, there where a couple of rules that I wanted to have in place:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;If I push an update to anything that would impact the site (styles, posts, templates), the system should deploy.&lt;/li&gt;&lt;li&gt;If I push changes that include new posts, the system should add the appropriate timestamps to the relevant posts before deploying. The timestamp additions should be commited and pushed back to the main repo before deploying.&lt;/li&gt;&lt;li&gt;I should be able to manually deploy, either by going through the gitlab UI, or by pushing a commit that includes a specific tag (&lt;code&gt;[deploy]&lt;/code&gt;)&lt;/li&gt;&lt;li&gt;I should be able to say that a commit should skip CI, even if it would normally trigger it, using a tag (&lt;code&gt;[noci]&lt;/code&gt;)&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;Most of this sounds pretty basic, but it was a surprising amount of effort to get things set up right. The first big snag was that GitLab doesn&apos;t have built-in support for pushing changes back to the repo from the CI pipeline. There are ways to do it, but it was surprisingly convoluted for something I would expect to be reasonably common.&lt;/p&gt;&lt;p&gt;The second thing, and this is probably the most pressing matter relating to this site at the moment, is that building the site for deployment takes almost an &lt;i&gt;hour&lt;/i&gt;. From what I can tell, this is because &lt;i&gt;stack&lt;/i&gt; (the Haskell build tool) has to download and compile Hakyll and its dependencies before compiling the site. However, there are solutions to this: The most promising one I found is the one documented in &lt;a href=&quot;https://sakshamsharma.com/2018/03/docker-hakyll-builds/&quot;&gt;this blog post&lt;/a&gt; by Saksham Sharma. I did try using the provided docker image, but due to an issue with locale info being unset in pure nix shells&lt;sup id=&quot;fnr-2&quot; class=&quot;footnote-ref&quot; data-label=&quot;2&quot;&gt;&lt;a href=&quot;#fn-2&quot;&gt;[2]&lt;/a&gt;&lt;/sup&gt; (I suspect), the site won&apos;t build properly. I expect I&apos;ll be looking into this pretty soon.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h3&gt;Python helper scripts&lt;/h3&gt;&lt;p&gt;As any good software developer, I want to automate as much of the process as possible, and the first obstacle I ran into was related to timestamping posts, both for first publish and for subsequent updates. Beyond that, I also wanted an easy way to move files from the drafts directory to the published posts, adding the required data while doing so.&lt;/p&gt;&lt;div class=&quot;section&quot;&gt;&lt;h4&gt;&lt;a href=&quot;https://gitlab.com/thomasheartman/blog/blob/master/scripts/add_timestamps.py&quot;&gt;~add_timestamps.py~&lt;/a&gt;&lt;/h4&gt;&lt;p&gt;A pretty simple script meant to be run in CI. It goes through all the posts with &apos;published&apos; tags that have changed since last push and adds the current timestamp. If a file has no value for the &apos;published&apos; tag, the current time is added, else, it adds or updates the &apos;modified&apos; tag with the current time.&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h4&gt;&lt;a href=&quot;https://gitlab.com/thomasheartman/blog/blob/master/scripts/publish.py&quot;&gt;~publish.py~&lt;/a&gt;&lt;/h4&gt;&lt;p&gt;To automate moving files between directories and adding the &apos;published&apos; tag to drafts, I wrote a simple script that does just that. Super easy. This led me to my first real revelation using &lt;code&gt;nix-shell&lt;/code&gt; (still just scratching the surface here), where I could package this script and use it as a command anywhere! I was super excited until I failed at packaging it correctly due to the dependencies on &lt;code&gt;hakyll.py&lt;/code&gt; ... This hasn&apos;t been resolved yet, but I&apos;ll figure it out at some point!&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h4&gt;&lt;a href=&quot;https://gitlab.com/thomasheartman/blog/blob/master/scripts/hakyll.py&quot;&gt;~hakyll.py~&lt;/a&gt;&lt;/h4&gt;&lt;p&gt;This is just some shared functions that deal specifically with Hakyll and my specific system. Most notably: lets you get metadata as a dict, update metadata values, sort tags, decide whether a post is new or updated and whether it is published at all. Also my first time using type annotations in Python (I don&apos;t actually know whether I did it right, but the system isn&apos;t complaining so far?), so that&apos;s a win.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;In closing&lt;/h2&gt;&lt;p&gt;In short, this has been a very enlightening and rewarding experience, and while I&apos;m certainly glad that to have gone through it, I am looking forward to not having to worry about it for a while (&lt;i&gt;hah, as if&lt;/i&gt;).&lt;/p&gt;&lt;p&gt;Now, let&apos;s get writing!&lt;/p&gt;&lt;/div&gt;&lt;div class=&quot;section&quot;&gt;&lt;h2&gt;Footnotes&lt;/h2&gt;&lt;p&gt;&lt;sup id=&quot;fnr-1&quot; class=&quot;footnote-ref&quot; data-label=&quot;1&quot;&gt;&lt;a href=&quot;#fn-1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt; &lt;a href=&quot;https://github.com/netlify/build-image/issues/251&quot;&gt;GitHub issue: Add support for Haskell&lt;/a&gt; &lt;sup id=&quot;fnr-2&quot; class=&quot;footnote-ref&quot; data-label=&quot;2&quot;&gt;&lt;a href=&quot;#fn-2&quot;&gt;[2]&lt;/a&gt;&lt;/sup&gt; &lt;a href=&quot;https://github.com/jaspervdj/hakyll/issues/614&quot;&gt;GitHub issue: &quot;hakyll can&apos;t handle unicode?&quot;&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;</content:encoded></item></channel></rss>