<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chris Grounds on Medium]]></title>
        <description><![CDATA[Stories by Chris Grounds on Medium]]></description>
        <link>https://medium.com/@iamchrisgrounds?source=rss-8a5b6bbfbe01------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*g65XXli_8bWEmNfwSNe9UQ.jpeg</url>
            <title>Stories by Chris Grounds on Medium</title>
            <link>https://medium.com/@iamchrisgrounds?source=rss-8a5b6bbfbe01------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:58:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamchrisgrounds/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why the funny names?]]></title>
            <link>https://medium.com/@iamchrisgrounds/why-the-funny-names-c7b17d396a35?source=rss-8a5b6bbfbe01------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7b17d396a35</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[category-theory]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Chris Grounds]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 06:34:20 GMT</pubDate>
            <atom:updated>2025-08-13T06:34:20.492Z</atom:updated>
            <content:encoded><![CDATA[<p>Monads, monoids, semigroups, functors; functional programmers love to make use of this type of vocabulary to describe software, and at first glance it can seem intimidating and abstruse. Why do we need to know, as the common joke goes, that a monad is just a monoid in the category of endofunctors? And what value is category theory and related mathematics to the field of software engineering anyway? An occasional complaint I’ve seen is that this type of language is too difficult and obscure to learn and we should just stick to more “ordinary” names and concepts.</p><p>I think there are a couple different things to say to this challenge. Firstly, it should be noted that what we consider ordinary is really just a historical accident, and it could well have been that the programming and software engineering community had settled on categorical concepts from the very beginning. In which case, junior software engineers would learn from the start of their careers what it means to compose two monads together via a monad transformer. Instead the industry went down a different avenue and things like monads appear to be big and scary concepts.</p><p>Secondly, I would agree that these concepts can be challenging to learn. But generally the best things are. And moreover the reason for the challenge is that these concepts are <em>universal</em>. They apply across all languages (in fact, they apply across all of mathematics, but that’s not of too much concern for the programmer interested in building composable software). For example, a functor in Haskell is a functor in Java is a functor in Javascript is a functor in Go, and on and on. These concepts cross all language barriers, and yes they can be daunting at first, but they are learn-once and apply everywhere concepts. What does Haskell’s »=, Rust’s and_then, Scala’s flatMap, and Javascript’s then have in common? They might seem completely unrelated, but they are essentially the same function: they all compose monads. Once you’re familiar with these concepts you can jump from language to language like jumping from car to car once you’ve learnt how to drive.</p><p>Thirdly, and related to the second point these concepts provide a shared-basis for mutual understanding. You’ll notice that each language I listed above has different names for the same idea. Rather than re-invent new words every time we create a new language I’d think it much better to reuse shared concepts: and there really is no better language to use for shared concepts than mathematics. And category theory is the language of composition, and is really by extension the language of software engineering (a field so intimately concerned about <em>how to compose</em>). Of those questioning the use of categorical language and vocabulary I would really have to ask: why would we not? As a domain driven designer would say, our domain is software itself and our ubiquitous language is the language of mathematics.</p><p>Fourthly, another benefit of using these mathematical terms and concepts is that they often have a long history and etymology, which can be helpful in aiding and deepening understanding. The word “algebra” comes from the Arabic root “al-jabr” which means something like “to reunite/reunion.” So an algebra is something which reunites things. Similarly “catamorphism” comes from the Greek “kata” meaning something like “downwards” and “morph” meaning “form/shape”, i.e. “down + shape”. The root “kata” here is the one found in English words like “<em>cata</em>strophe”. So a catamorphism is what most languages call the reduce or fold functions, as they are taking a structure or shape and turning it into a single (downward movement) value. The reverse of a catamorphism is called an “anamorphism.” The root here is “ana” meaning “upward”. So the inverse of a catamorphism takes a single value and turns it upward into a shape/form, or unfold. Putting these three concepts together we’ve just rediscovered what are called “recursion schemes.” A catamorphism takes an algebra (a definition of how to reunite things) and performs the downward movement to a single form, and an anamorphism does the inverse. Of course, etymology is not enough by far and these concepts can take a bit of work to understand. But the trade-off is that like learning to ride a bike once we know them we know them and can apply them to all languages.</p><p>So all in all I think there are very good reasons for using the funny names that functional programmers are so fond of. We shouldn’t reinvent the linguistic wheel but should build upon the solid foundations we find at our disposal. And let’s not forget that naming is a very hard problem — a problem that is solved in this instance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7b17d396a35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Domain Modelling with Category Theory]]></title>
            <link>https://medium.com/@iamchrisgrounds/domain-modelling-with-category-theory-e3cf8cb8ed74?source=rss-8a5b6bbfbe01------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3cf8cb8ed74</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[category-theory]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Chris Grounds]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 09:51:32 GMT</pubDate>
            <atom:updated>2024-11-01T09:51:32.476Z</atom:updated>
            <content:encoded><![CDATA[<p>Gandalf finds himself sitting at his computer one rainy Wednesday and in a moment of procrastination loads up his favourite online staff shop. He finds the latest newly released staff, that all his wizarding friends have been raving about, and loads the product page. His mouse tantalizingly hovers over the “add to basket” button until his impulsiveness gets the better of him and… he clicks.</p><p>Gandalf doesn’t need a new staff. His old one is more than up to the task, having helped defeat &lt;spoiler&gt;. And as fun as this story is you’re a software engineer, and you’d much rather know how to model this user journey than find out whether Gandalf went through and bought the new staff.</p><p>So how can we model this process and how can we use Category Theory to help?</p><p>In OO-land, we might create a Basket class along with an addItem(Item item) method. But we can think about this interaction differently. Rather than thinking about the user adding an item to a basket, we can think about the user adding a basket to a basket. Let’s forget about items for the minute, and just think about how this would work if we constrain ourselves to baskets?</p><p>To begin with, the user adds a basket containing something to an already existing basket. This already existing basket must be empty because it’s the first item to be added (so this first basket functions as a no-op). Then any additional items are additional baskets being added to the previous basket.</p><p>Another crucial feature of our basket model is that the order in which baskets are added together doesn’t matter. That is, if I add my wine_basket with my cheese_basket, and add that basket with my bread_basket, then that’s going to give me the same final basket as adding my cheese_basket with my bread_basket, and then adding that to my wine_basket. In the end I end up with wine, cheese, and bread. In other words, our baskets are <em>associative</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*6GK8umUfBreSdiVUiwCp0g.png" /><figcaption>(wine + cheese) + bread = wine + (cheese + bread)</figcaption></figure><p>In the language of category theory, our basket model forms a <em>semigroup </em>as we‘ve defined a binary associative operator on it, and it forms a <em>monoid </em>because additionally we’ve given it an identity value — the empty basket. Let’s call our binary associative operator “append” and we can see how we might think about semigroups and monoids pictorially.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*B2um3edDvkgX_ZUZFs_6ew.png" /><figcaption>A categorical image of semigroups and monoids, expressing the arrows with their relevant type-signature. You can read “::” as “has type”.</figcaption></figure><p>A common example of a semigroup is the positive natural numbers (1..) where the binary associative operator is addition, and an example of a monoid is the natural numbers (0..) where the identity value is 0. Naturally, 0 is the identity value as <em>n + 0 = n</em>. Incidentally, in OOP, we can think of the Builder pattern as a monoid. The initial Builder construction is the identity value, and withX methods are binary associative operations from Builder to Builder.</p><pre>// identity value<br>new CarBuilder()<br>  // binary associative function withWheels<br>  // takes a CarBuilder and returns a CarBuilder<br>  .withHeadlights()<br>  .withEngine()<br>  .withWheels(4)<br>  .build();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*sf70Jg-jmWkcUd-988glFw.png" /><figcaption>Builder as a monoid</figcaption></figure><p>In Rust, we can define two traits, <em>Semigroup</em> and <em>Monoid</em>,<em> </em>to represent these categorical concepts. Semigroup contains a binary function, which we’ve called sappend to differentiate it from the monoidal definition. Monoid contains mappend (essentially Semigroup’s sappend) and an mempty value to represent identity. We give the functions such strange names because append is generally used in languages for List-type structures (“sappend”: semigroup-append, and “mappend”: monoid-append), and we call the identity value mempty because it generally represents an empty variant of a type and id would either be confusing or reserved.</p><pre>trait Semigroup {<br>    fn sappend(self, b: Self) -&gt; Self;<br>}<br><br>trait Monoid: Semigroup {<br>    fn mempty() -&gt; Self;<br>    fn mappend(self, b: Self) -&gt; Self;<br>}</pre><p>Let’s define our Basket type. And for the sake of brevity, we’ll just assume Bucket stores items in a Vector and we won’t care about the Item type itself.</p><pre>struct Basket {<br>    items: Vec&lt;Item&gt;<br>}</pre><p>With this, we can define how we add two Basket’s together,</p><pre>impl Semigroup for Basket {<br>    fn sappend(self, b: Basket) -&gt; Basket {<br>        Basket { items: self.items.into_iter().chain(b.items).collect() }<br>    }<br>}</pre><p>And to define our Basket as a monoid, we can piggyback on our Semigroup definition and simply provide an identity value,</p><pre>impl Monoid for Basket {<br>    fn mempty() -&gt; Basket {<br>        Basket { items: vec![] }<br>    }<br>    <br>    fn mappend(self, b: Basket) -&gt; Basket {<br>        self.sappend(b)<br>    }<br>}</pre><p>With this in place we can construct our basket by first creating an empty basket and then adding additional baskets.</p><pre>let basket1 = Basket { items: vec![Item(&quot;apple&quot;.to_string())] };<br>let basket2 = Basket { items: vec![Item(&quot;orange&quot;.to_string())] };<br><br>Basket::mempty()<br>  .mappend(basket1)<br>  .mappend(basket2);<br><br>// Result: Basket { items: [Item(&quot;apple&quot;), Item(&quot;orange&quot;)] }</pre><p>Now whenever the user clicks “add to basket”, we simply mappend another basket to the current basket.</p><p>Let’s extend the requirements here: suppose we want the user to be able to see a history of their basket and revert to a certain point. This is actually fairly simple with our monoidal structure.</p><p>But first, let’s consider our OO-Basket class. In order to go back in time we’d have to create a removeItem method, keep track of when addItem was called, with what, and with how much, and then call removeItem on any items that were added after a certain point. This would work, but it feels messy.</p><p>With the monoidal approach, all we need is to keep track of what Basket’s existed and when. Once the user selects a time to revert their basket to, the monoidal nature of the Basket type means we simply append all the previous versions together — and because of the associative nature of monoids, the order of application doesn’t matter. (And this works because fundamentally adding things to a basket is associative — the order of adding things doesn’t matter. You can try this out in a supermarket!)</p><p>So if we store our Baskets in a Vector or List type along with a timestamp (representing when they were created), we can fold over the Vec/List (itself a monoid) and rebuild our Basket to the desired point in time. To do this we filter our stored baskets to include only those before our desired time and then fold over the result, calling mappend on each iteration to build up our new Basket. The initial value is the identity value (Basket::mempty) so if there is nothing to fold over, we always have at least an empty Basket.</p><pre>struct BasketHistory {<br>    saved_states: Vec&lt;(SystemTime, Basket)&gt;<br>}<br><br>impl BasketHistory {<br>    fn recover_to_time(&amp;self, target_time: SystemTime) -&gt; Basket {<br>        self.saved_states<br>            .iter()<br>            .filter(|(time, _)| time &lt;= &amp;target_time)<br>            .map(|(_, basket)| basket.clone())<br>            .fold(Basket::mempty(), |acc, basket| acc.mappend(basket))<br>    }<br>}</pre><p>This suddenly feels very much like a lightweight version of event-sourcing, which we’re almost getting for free. The difference is we’re not explicitly creating events and we don’t care about processing sequentially. This all comes down to the fact our core computation is a binary associative operator, which gives us a branching structure. (Incidentally, this branching structure — think of how (1+(2+(3+4))+(4+(3+(2+1)))) is also branching — actually gives us thread-safe code that could be parallelized.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*VHTRS3piurU7V7HRlJe7Gg.png" /><figcaption>It’s Baskets all the way down</figcaption></figure><p>Before going down too much of a rabbit-hole, let’s take stock. With just two concepts from category theory, we’ve been able to rigorously and iteratively model a very common process. We’ve done this just by thinking about how we compose base elements together in a way that respects relatively straightforward rules (namely, associativity and identity). This is just touching on the surface of what category theory has to offer us when it comes to domain modelling and building robust software. But for now, I think Gandalf would be happy knowing his Basket is a proper monoidal object.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3cf8cb8ed74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Generate Random Data in Rust]]></title>
            <link>https://medium.com/@iamchrisgrounds/how-to-generate-random-data-in-rust-7433568af673?source=rss-8a5b6bbfbe01------2</link>
            <guid isPermaLink="false">https://medium.com/p/7433568af673</guid>
            <category><![CDATA[randomness]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[testing-tools]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Chris Grounds]]></dc:creator>
            <pubDate>Fri, 17 Mar 2023 13:23:17 GMT</pubDate>
            <atom:updated>2023-03-17T13:23:17.580Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you looking to generate random data for testing or demo purposes? Look no further than Rust, a systems programming language that provides excellent memory safety and performance. In this tutorial, we’ll walk through the steps of using Rust’s rand::distributions library to generate random sensor data and write it to a CSV file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*S3Wa-bRdqhH-_8MqxdWFrQ.png" /><figcaption>Randomly generated data in csv format</figcaption></figure><p>First, let’s create a new Rust project by running cargo new random-sensor-data. This will create a new directory with the basic structure of a Rust project.</p><p>Next, we need to add some dependencies to our project. Open the Cargo.toml file and add the following lines:</p><pre>[dependencies]<br>rand = &quot;0.8.4&quot;<br>serde = { version = &quot;1.0&quot;, features = [&quot;derive&quot;] }<br>strum = &quot;0.19.10&quot;<br>strum_macros = &quot;0.19.10&quot;<br>csv = &quot;1.1.7&quot;</pre><p>These dependencies will allow us to generate random numbers, serialize and deserialize data, define enums with string representations, and write to CSV files.</p><p>Now, let’s create a new Rust file called event_data.rs. In this file, we&#39;ll define a new data type called EventData that represents a sensor event. We&#39;ll also define an enum called EventType that represents the different types of sensor events.</p><pre>use rand::distributions::{Distribution, Standard};<br>use rand::Rng;<br>use serde::Serialize;<br>use strum::EnumCount;<br>use strum_macros::{EnumCount as EnumCountMacro, EnumIter};<br><br>#[derive(Debug, EnumCountMacro, EnumIter, Serialize)]<br>pub enum EventType {<br>    SensorTriggered,<br>    SensorAcknowledged,<br>    SensorOff,<br>}<br><br>#[derive(Debug, Serialize)]<br>pub struct EventData {<br>    pub event_type: EventType,<br>    pub timestamp: u64,<br>    pub correlation_id: u64,<br>}</pre><h3>Defining the Distribution Implementation for EventData</h3><p>Now that we’ve defined our EventData type and its possible variants, we need to tell Rust how to randomly generate data for this type. We can do this by implementing the Distribution trait from the rand crate.</p><p>We’ll start by defining our implementation of the Distribution trait for EventData in event_data.rs:</p><pre>use rand::distributions::{Distribution, Standard};<br>use rand::Rng;<br>use serde::Serialize;<br>use strum::EnumCount;<br>use strum_macros::{EnumCount as EnumCountMacro, EnumIter};<br><br>#[derive(Debug, EnumCountMacro, EnumIter, Serialize)]<br>pub enum EventType {<br>    SensorTriggered,<br>    SensorAcknowledged,<br>    SensorOff,<br>}<br><br>#[derive(Debug, Serialize)]<br>pub struct EventData {<br>    pub event_type: EventType,<br>    pub timestamp: u64,<br>    pub correlation_id: u64,<br>}<br><br>impl Distribution&lt;EventData&gt; for Standard {<br>    fn sample&lt;R: Rng + ?Sized&gt;(&amp;self, rng: &amp;mut R) -&gt; EventData {<br>        let (timestamp, correlation_id) = rng.gen();<br>        let event_type = match rng.gen_range(0..=(EventType::COUNT - 1)) {<br>            0 =&gt; EventType::SensorAcknowledged,<br>            1 =&gt; EventType::SensorTriggered,<br>            _ =&gt; EventType::SensorOff,<br>        };<br>        EventData {<br>            event_type,<br>            timestamp,<br>            correlation_id,<br>        }<br>    }<br>}</pre><p>This implementation uses the gen() method from the Rng trait to generate a random timestamp and correlation ID for the event. It then generates a random EventType by generating a random integer between 0 and the number of variants in the EventType enum, and matching on the result to select one of the possible EventType variants.</p><p>What’s interesting here is that we have defined our own custom datatype and told Rust how it should generate random events of that type. Then when we come to actually generate the data, Rust will use the definition we’ve given above for Distribution&lt;EventData&gt;.</p><h3>Writing the Generated Data to CSV</h3><p>Now that we can generate random EventData instances, we need to write them to a CSV file. We&#39;ll do this in main.rs using the csv crate. Here&#39;s our implementation:</p><pre>use csv::Writer;<br>use event_data::EventData;<br>use rand::Rng;<br>use std::error::Error;<br>use std::fs::File;<br>use std::time::Instant;<br>mod event_data;<br><br>fn write_event_to_csv(wtr: &amp;mut Writer&lt;File&gt;, event_data: EventData) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {<br>    wtr.serialize(&amp;event_data)?;<br>    wtr.flush()?;<br>    Ok(())<br>}<br><br>fn main() {<br>    let total_events = 10000;<br>    let mut rng = rand::thread_rng();<br>    let mut wtr = Writer::from_path(&quot;random_data.csv&quot;).unwrap();<br><br>    let now = Instant::now();<br><br>    for _ in 0..total_events {<br>        let random_event: EventData = rng.gen();<br><br>        write_event_to_csv(&amp;mut wtr, random_event).unwrap();<br>    }<br><br>    println!(&quot;Finished in {:?}!&quot;, now.elapsed());<br>}</pre><p>We start by defining a helper function called write_event_to_csv that takes a reference to a CSV writer and an EventData instance, and writes the event data to the CSV. We use the serialize method of the Writer to write the EventData instance as a row in the CSV file. We then call the flush method to ensure that the data is written to disk.</p><p>In main, we create a Writer instance that writes to a file called random_data.csv. We then generate a total of 10,000 random EventData instances using the gen() method from the Rng trait, and write each instance to the CSV file using our write_event_to_csv function.</p><h3>Conclusion</h3><p>In this article, we’ve seen how to use Rust’s rand crate to generate random data and write it to a CSV file. We&#39;ve defined a custom data type, implemented the Distribution trait for it, and used the csv crate to write the generated data to disk. By leveraging Rust&#39;s strong typing and expressive syntax, we&#39;ve created a robust and reliable system for generating and writing random data for custom datatypes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7433568af673" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Sheets with Rust]]></title>
            <link>https://medium.com/@iamchrisgrounds/google-sheets-with-rust-6ecab23fa765?source=rss-8a5b6bbfbe01------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ecab23fa765</guid>
            <dc:creator><![CDATA[Chris Grounds]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 21:02:57 GMT</pubDate>
            <atom:updated>2023-02-23T21:02:57.724Z</atom:updated>
            <content:encoded><![CDATA[<p>So you want to use Google Sheets as your serverless database and you want to use Rust to query it. Excitedly, you find there is a Rust API for it. Eager to get started you copy the API documentation’s getting-started example into a brand new Rust repo.</p><p>Compilation error! Don’t worry, you search google for more examples and you find a dev.to article on this very topic. So you copy the example from the dev.to blog and paste it into your newly established Rust repo.</p><p>Compilation error! In fact, the error is irrecoverable because the versions are wrong to begin with. Nevermind, let’s start again.</p><p>Before we begin there is something you need to understand about the Google APIs. You will have to authenticate. And authentication happens either through (a) API keys, which we can forget about because they only give us readonly access to Google Sheets, (b) OAuth, which we can ignore because we only want to use the API for our own Sheets — this is just overkill, or (c) service account credentials.</p><p>We will be using service account credentials. But this post is not about getting your service account credentials. It is really very easy, all you need to do is go to Google Console and create a Service Account. From there download the private key file and put it in the root of the repo at `priv_key.json`. That’s basically it but there are many many guides on this part.</p><p>No, we’re interested in the Rust part of this story.</p><p>The key ingredients for this code will be the aforementioned google_sheets4 Rust API, with non-compiling examples, someway to create a HTTP client, someway to create authentication, and then putting it all together to construct a request to the Google Sheets API.</p><p>Let’s begin. First with the <strong>HTTP Client</strong>.</p><pre>// main.rs<br>async fn main() {<br>  let client = http_client::http_client();</pre><pre>// http_client.rs<br>use sheets4::{hyper, hyper_rustls};<br><br>pub fn http_client() -&gt; hyper::Client&lt;hyper_rustls::HttpsConnector&lt;hyper::client::HttpConnector&gt;&gt; {<br>    return hyper::Client::builder().build(<br>        hyper_rustls::HttpsConnectorBuilder::new()<br>            .with_native_roots()<br>            .https_only()<br>            .enable_http1()<br>            .enable_http2()<br>            .build(),<br>    );<br>}</pre><p>This client will be used for both the authentication request and the Google Sheets API request.</p><p>Then the code we need for <strong>Authentication</strong>.</p><pre>async fn main() {<br>    let config = config::Config::new();<br>    let client = http_client::http_client();<br>    let auth = auth::auth(&amp;config, client.clone()).await;</pre><pre>// auth.rs<br>use sheets4::oauth2::{self, authenticator::Authenticator};<br>use sheets4::{hyper, hyper_rustls};<br><br>use crate::config::Config;<br><br>pub async fn auth(<br>    config: &amp;Config,<br>    client: hyper::Client&lt;hyper_rustls::HttpsConnector&lt;hyper::client::HttpConnector&gt;&gt;,<br>) -&gt; Authenticator&lt;hyper_rustls::HttpsConnector&lt;hyper::client::HttpConnector&gt;&gt; {<br>    let secret: oauth2::ServiceAccountKey = oauth2::read_service_account_key(&amp;config.priv_key)<br>        .await<br>        .expect(&quot;secret not found&quot;);<br><br>    return oauth2::ServiceAccountAuthenticator::with_client(secret, client.clone())<br>        .build()<br>        .await<br>        .expect(&quot;could not create an authenticator&quot;);<br>}</pre><p>This code depends on a <strong>Config </strong>struct I created, which I use to store various bits of config.</p><pre>// config.rs<br>pub struct Config {<br>    pub priv_key: String,<br>    pub sheet_id: String,<br>    pub deposit_range_input: String,<br>    pub deposit_range_output: String,<br>}<br><br>impl Config {<br>    pub fn new() -&gt; Config {<br>        Config {<br>            priv_key: String::from(&quot;priv_key.json&quot;),<br>            sheet_id: String::from(&quot;sheet_id&quot;),<br>            deposit_range_input: String::from(&quot;Deposits Stream!A2:B&quot;),<br>            deposit_range_output: String::from(&quot;Deposits Stream!G1&quot;),<br>        }<br>    }<br>}</pre><p>It assumes you store the Service Account credentials in priv_key.json at the root of the repo.</p><p>Now we have a HTTP client and authentication taken care off, we can construct and make our request to our Google Sheet.</p><pre>async fn main() {<br>    let config = config::Config::new();<br>    let client = http_client::http_client();<br>    let auth = auth::auth(&amp;config, client.clone()).await;<br>    let mut hub = Sheets::new(client.clone(), auth);<br><br>    let result = sheets::read(&amp;hub, &amp;config).await;</pre><pre>// sheets.rs<br>use sheets4::{api::ValueRange, hyper, hyper_rustls, Error, Sheets};<br><br>use crate::config::Config;<br><br>pub async fn read(<br>    hub: &amp;Sheets&lt;hyper_rustls::HttpsConnector&lt;hyper::client::HttpConnector&gt;&gt;,<br>    config: &amp;Config,<br>) -&gt; Result&lt;(hyper::Response&lt;hyper::Body&gt;, ValueRange), Error&gt; {<br>    return hub<br>        .spreadsheets()<br>        .values_get(&amp;config.sheet_id, &amp;config.deposit_range_input)<br>        .doit()<br>        .await;<br>}</pre><p>With the result variable in main.rs, we can now pattern match on it as it returns a Result. This will then allow us to destructure it and iterate over the sheet data. In my case I want to reduce a column of data into a Hashmap.</p><pre>// main.rs<br>match result {<br>        Err(e) =&gt; println!(&quot;{}&quot;, e),<br>        Ok((_, spreadsheet)) =&gt; {<br>            let totals = HashMap::&lt;String, i32&gt;::new();<br><br>            println!(<br>                &quot;Success: {:?}&quot;,<br>                spreadsheet<br>                    .values<br>                    .unwrap()<br>                    .into_iter()<br>                    .fold(totals, |mut acc, next_row| {<br>                        let key: String = next_row[0].clone();<br>                        let current_value: Option&lt;&amp;i32&gt; = acc.get(&amp;key);<br>                        let next_value: i32 = next_row[1].parse::&lt;i32&gt;().unwrap();<br><br>                        let new_value: i32 = match current_value {<br>                            None =&gt; next_value + 0,<br>                            Some(x) =&gt; next_value + x,<br>                        };<br><br>                        acc.insert(key, new_value);<br><br>                        return acc;<br>                    })<br>            );<br>        }<br>    }</pre><p>The important thing here is that to access the data from the API call we just need to call spreadsheet.values.</p><p>I don’t know if that’s helpful but you can find all of the code together as a complete example here: <a href="https://github.com/chrisgrounds/finance-sheet">https://github.com/chrisgrounds/finance-sheet</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ecab23fa765" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Problem with Typescript’s Types]]></title>
            <link>https://medium.com/@iamchrisgrounds/the-problem-with-typescripts-types-1ee92ba7ec39?source=rss-8a5b6bbfbe01------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ee92ba7ec39</guid>
            <category><![CDATA[type]]></category>
            <category><![CDATA[type-safety]]></category>
            <category><![CDATA[haskell]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Chris Grounds]]></dc:creator>
            <pubDate>Tue, 14 Feb 2023 11:13:27 GMT</pubDate>
            <atom:updated>2023-02-14T11:13:27.146Z</atom:updated>
            <content:encoded><![CDATA[<p>A recent <a href="https://twitter.com/mattpocockuk/status/1625173884885401600">twitter thread by Matt Pocock</a> has raised some interesting points around Typescript’s type-system, principally around how it’s not doing a good job as a type-system. To see why, consider some code where we create a User and an AdminUser along with a function that only accepts objects of type User. In Typescript this will look like this:</p><pre>type User      = { name: string };<br>type AdminUser = { name: string };<br><br>const f = (a: User): boolean =&gt; true;<br><br>const admin: AdminUser = { name: &quot;Chris&quot; };<br><br>console.log(f(admin));</pre><p>Typescript will happily compile this code and when run it will print out the result of our function. But this code <strong>should not</strong> compile; it should result in a compilation/type error, because we’ve typed our function to take a User but we’ve been able to erroneously give it an AdminUser.</p><p>This is the problem that the Matt Pocock thread is solving — through the use of Branded types. However, this is really something the type-system itself should handle without forcing the developer to jump through hoops. The problem here is naturally that everything is an object and types in Typescript are really just interfaces to those objects. So when you write type User = { name: string } you’re not actually creating a User type, you’re just creating an interface to the object { name: string } — which AdminUser also satisfies. And therefore you can use these two types interchangeably.</p><p>Let’s look at how a real type-system would handle this problem. In Rust[1] we can write the code as follows,</p><pre>struct User {<br>  name: String<br>}<br><br>struct AdminUser {<br>  name: String<br>}<br><br>fn f(a: User) -&gt; bool {<br>  return true;<br>}<br><br>fn main() {<br>  let a: AdminUser = AdminUser { name: String::from(&quot;Chris&quot;) };<br><br>  println!(&quot;{}&quot;, f(a));<br>}</pre><p>This, <em>correctly</em>, does not compile and errors with the following compilation error:</p><pre>- ^ expected struct `User`, found struct `AdminUser`</pre><p>This also goes back to the recent debate in the Typescript community about whether Typescript code should have <em>explicit return types</em> or just use <em>inference</em>. The reason this debate even exists in Typescript is because explicit return types <a href="https://www.youtube.com/watch?v=I6V2FkW1ozQ">don’t tell the truth </a>— as we’ve seen in the above Typescript code, a function that says it only accepts a User type can in actual fact accept a much wider range of types.</p><p>So to conclude is this a warning to not use Typescript? No, it’s not. But it is a warning to use the right tool for the job. If you need basic type safety and don’t want to jump through some — frankly ridiculous — hoops, then Typescript is probably not the tool for the job.</p><p>[1] This is obviously not just a feature of Rust, consider Haskell:</p><pre>newtype User      = User String<br>newtype AdminUser = AdminUser String<br><br>f :: User -&gt; Bool<br>f a = True<br><br>main = print $ f (AdminUser &quot;Chris&quot;)</pre><p>Produces:</p><pre>Couldn&#39;t match expected type &#39;User&#39; with actual type &#39;AdminUser&#39;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ee92ba7ec39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are Humans Value Objects or Entities?]]></title>
            <link>https://medium.com/@iamchrisgrounds/are-humans-value-objects-or-entities-5ee34ac197dd?source=rss-8a5b6bbfbe01------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ee34ac197dd</guid>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Chris Grounds]]></dc:creator>
            <pubDate>Mon, 29 Aug 2022 15:52:13 GMT</pubDate>
            <atom:updated>2022-08-29T15:52:13.814Z</atom:updated>
            <content:encoded><![CDATA[<p>There’s an old philosophical thought experiment that goes like this: Suppose there is a machine that renders you unconscious and makes an exact copy of you down to the smallest detail, preserving your neural connections and molecular makeup. It then sends this data to Mars where another machine reconstructs you, recreating every connection and placing every atom in the same position relative to other atoms. In one variation of this thought experiment the machine obliterates the original copy of you, leaving only the copy on Mars, and in another it leaves the one on Earth intact.</p><p>Philosophically, this is an interesting thought experiment because it helps us delve into issues around personal identity. But let’s suppose this is the real world. <em>How would a software engineer model this domain</em>?</p><p>In the arsenal of Domain Driven Design (DDD), there are two concepts that may be useful here: Value objects and Entities.</p><p>Value Objects are objects that are replaceable like-for-like — £10 can be replaced with another £10 and nothing will have changed. They are immutable and their identity is determined purely by their attributes. The canonical example of a Value object is a point on a Cartesian co-ordinate system: Point(10, 11) is identical to Point(10, 11) by virtue of them both being located at 10 on the x-axis and 11 on the y-axis. That’s it.</p><p>Entities on the other hand are objects that have some conceptual identity to them. They are mutable and because of that their identity is not determined by their attributes. The canonical example is an airplane. Two airplanes may have the same attributes — fuel load, number of wings, etc — but they are distinct objects that we can distinguish with, for example, a unique PlaneId.</p><p>So the question is, in a world in which you can be cloned like-for-like and sent to Mars, are humans Value objects or Entities in the language of DDD?</p><p>In the column for Value objects, a natural intuition is to perhaps to say that if you have been re-created perfectly exactly down to the atomic level, including all your neural connections — which presumably make up your thoughts and feelings — then the copy of you on Mars <em>is you!</em> Not just a copy of you, but it really is you, as much as the Earth version is. The Martian version thinks the same thoughts, has the same memories, has the same feelings. It is you and your identity is determined by your attributes — molecular makeup. This is a Value object.</p><p>So as software engineers we can model human beings as Value objects that consist of a set of attributes (molecular makeup and neural relations, or even just atoms). Thus, we can create a new Human({ …atoms }) object and compare identity between two clones by checking just their atoms. However, this model will fall down when we realise humans are constantly changing beings — our hair grows and we are always creating new neural connections. We might want to model this by saying that in every new moment, your past self dies and a new Value object is created. Something like this,</p><pre>const chris10MinsAgo = new Human({ ...oldAtoms })<br>const chrisNow = new Human({ ...newAtoms })</pre><p>But this would make the software very difficult to work with, as we’d have no way of tracking who was who in the past. It may or may not be an accurate description of reality, but it would make it hard or impossible to write any meaningful, working software.</p><p>The other option is to say that humans are actually Entities, defined by some identifier. This means in the thought experiment the copy of you on Mars is not you because identity is not attribute-identity. It would be easy to solve this problem by assigning a unique, random, SKU to each human at birth. Fortunately, humans aren’t products found on a distributor’s shelving — we don’t come with SKUs. So then what is the identifier going to be? Depending on your world view you might think there is some unique self or soul that identifies each of us.</p><pre>class Human {<br>  constructor() {<br>    this.id = new Soul();<br>  }<br>}</pre><p>This would be problematic for a number of reasons, most notably being humans probably don’t have souls.</p><p>On the other hand, Derek Parfit, who introduced/popularised the thought experiment, thought that what matters is psychological continuity and connectedness rather than identity <em>per se</em>. Identity is just an illusion and doesn’t really exist. This is just to say that what makes you <em>you </em>is that you have an overlapping set of experiences, memories, and general psychological state.</p><p>So perhaps we can model humans as being Entities that have a nebulous concept of identity. For example,</p><pre>class Human {<br>  constructor() {<br>    this.id = [ ...overlappingSetOfExperiencesMemoriesAndPsychologicalState ]<br>  }</pre><pre>  update(experience) {<br>    this.id.push(experience);<br>  }<br>}</pre><p>Identity is determined through having an overlapping set of experiences, memories and so on. This would mean earthHuman === marsHuman at the moment of conception of the clone, which we may not want. Of course, as soon as the clone’s experiences diverge from the original <em>you</em>, it would start to become a different and unique human/object.</p><p>That may only be small comfort if the clone immediately withdraws all your money from their/your bank account; it would be the <em>same</em> bank account because it’s the same Entity! And it must also be said that it really doesn’t make much sense for an Entity to be able to mutate its unique identifier, because then there is no guarantee it will not clash with another Entity’s identifier. But that may well be the world/domain we live in.</p><p>Really the problem with humans being Entities comes down to the fact that there isn’t really a sensible identifier we can use for human beings, at least not without admitting that the version of us on Earth is the same as the version on Mars. Maybe that’s exactly what we want once we talk to our domain experts.</p><p>But if in our domain the human on earth is <em>not</em> the same as the copy on Mars, then it’s not clear how we actually model that! At least not on a Bank Holiday afternoon.</p><p>All in all, DDD is hard, philosophy is harder, and identity is impossible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ee34ac197dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS Animations as a DOM-Based Animations Framework]]></title>
            <link>https://medium.com/bbc-product-technology/css-animations-as-a-dom-based-animations-framework-d6ef582c033a?source=rss-8a5b6bbfbe01------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6ef582c033a</guid>
            <category><![CDATA[games]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[domain-specific-languages]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Chris Grounds]]></dc:creator>
            <pubDate>Thu, 11 Feb 2021 10:19:02 GMT</pubDate>
            <atom:updated>2021-02-11T10:19:02.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bBIBV8KIob0fj2K8ZtadpQ.png" /></figure><p>This is the second post in a series about how BBC Children’s and Education have migrated from native-first apps to interactive app experiences as Progressive Web Apps (PWA). As we saw in the first blog post, very soon we will be launching four CBeebies apps, completing the migration of old embedded tech to modern web standards and APIs on the new Universal App Platform (UAP). Part of this process has involved creating a new, declarative animations framework and re-thinking how we use them. This blog will be focused on that, but you can read about the strategy and motivation behind the <a href="https://medium.com/bbc-design-engineering/shipping-progressive-web-apps-everywhere-190a421c606a">creation of UAP here</a>.</p><p>A large proportion of graphically intensive 2D web and app experiences use HTML Canvas or WebGL as their rendering target/API. This is true particularly because widely used rendering engines and frameworks, such as <a href="https://www.pixijs.com/">Pixi.js</a> and <a href="https://phaser.io/">Phaser.js</a>, output to WebGL and fallback to Canvas if WebGL is not available.</p><p>The benefit of using such libraries is that they provide a JavaScript API that achieves pixel-perfect precision and very high performance. The disadvantages of such an approach are that since they are not DOM-based they are not declarative, making them harder to reason about, harder to maintain, and harder to make accessible. Moreover, since they target pixels they are harder to make responsive and are at a disadvantage compared to DOM-based technologies.</p><p>In contrast to this, CSS Animations allow us to work with the DOM and can be composited onto the GPU, meaning we can achieve good performance with maintainable code. Overall, moving to the DOM has allowed us to build components in a more commoditised way, with the trade-off being high fidelity experiences.</p><p>UAP is not specifically a web-app, rather it is first-and-foremost a platform. Consequently, when developing the animations library we had to keep certain requirements in mind in order to make the library a good fit for any end-user. These requirements are that the animations must be:</p><ul><li>Reusable</li><li>Customisable and flexible</li><li>Easy and intuitive to use</li></ul><p>The way we have met these conditions lies in writing a React <a href="https://en.wikipedia.org/wiki/Domain-specific_language">Domain Specific Language</a> (DSL) sitting on top of CSS animations, thereby providing compositionality, re-usability, flexibility to customise, and ease-of-use: plug ‘n play animations for any consumer.</p><h3>The Animation Framework</h3><p>CSS animations provide a declarative API enabling the developer to animate a DOM node and its children. The developer only needs to define certain properties about the animation (i.e. its duration, any delay, its timing function) and then define some keyframes that describe what the animation will do at certain points (i.e. 50% of the way through make the background-color red). However, it would not be maintainable to litter our children’s apps with animation keyframes. They would appear disparate, hard to find, and would not be re-usable.</p><p>The first step towards our DSL is to create an animations component inside of UAP. The job of this component is simply to expose a set of re-usable animations. Any keyframes and CSS animations are to be placed here, thereby solving the above problems. The next step is to use JSX and React to abstract CSS animations. This gives effortlessly us a compositional API, which is key to the way we have layered multiple animations upon each other. This simply comes from the fact that JSX is inherently a compositional language, meaning we can take multiple JSX components and combine them to form a new JSX component. This is precisely how we create multi-layered animations: a zoom animation is combined with a fade animation to create a composite zoom-fade JSX component. Animations can be layered infinitely this way to create varied and novel animations.</p><h3>Zooming</h3><p>Let’s consider an example to make this more concrete. Here is the API for an animation which zooms into an object.</p><pre>&lt;Zoom <em>from</em>={1} <em>to</em>={1.3} <em>duration</em>={2} <em>delay</em>={0}&gt;<br>  &lt;RedBox&gt;<br>&lt;/Zoom&gt;</pre><p>As you can see Zoom takes a set of props:</p><ul><li>from-state (where it starts the animation)</li><li>to-state (where it ends it)</li><li>duration (how long it will take)</li><li>and a delay (how long the animation should wait before starting)</li></ul><p>It’s important that the API we expose to our DSL is consistent and intuitive, and of course each component supports React Synthetic Events such as onAnimationEnd, giving the developer complete control over ordering and timing events.</p><p>Here is Zoom in action in Storybook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*mhme3fV1p2yY3lw0ruIsMA.gif" /><figcaption>Zoom In Animation</figcaption></figure><p>Anyone consuming UAP components/modules can pull in Zoom from the animation component and configure it through a few props, as easy as above, and then compose it with their animation target to achieve a similar effect.</p><h3>Zooming internals</h3><p>So that’s what the consumer of Zoom sees and interfaces with, but how did we actually achieve that API?</p><p>We use <a href="https://styled-components.com/">styled-components</a> to create JSX components with tagged template literals and inline CSS. Styled components (or CSS in JSX more broadly) allows us to automatically scope styles, it removes the distinction between JSX and CSS which helps with re-usability, and provides an easy way to customise CSS through JS.</p><p>The syntax may look a little odd at first, but as you can see in the following snippet it is just CSS inside of a function/JSX component.</p><pre>const zoomKeyframe = (from, to) =&gt; keyframes`<br>  from {<br>    transform: scale(${from || 1})<br>  }</pre><pre>  to {<br>    transform: scale(${to || 1.3})<br>  }<br>`;</pre><pre><em>export</em> const Zoom = styled(AnimationLayer)`<br>  will-change: transform;<br>  ${({ from = 1, to, delay = 0, duration, rotate }) =&gt;<br>    css`<br>      animation: ${rotate<br>        ? zoomAndRotateKeyframe(from, to, rotate)<br>        : zoomKeyframe(from, to)}<br>      ${duration}s ${cubicBezier} both;<br>    animation-delay: ${delay}s;<br>  `}<br>`;</pre><h3>Fade</h3><p>Another example in use in the CBeebies Children’s apps are the Fade animations.</p><pre>&lt;FadeIn <em>duration</em>={2} <em>delay</em>={2}&gt;<br>  &lt;RedBox /&gt;<br>&lt;/FadeIn&gt;</pre><p>and</p><pre>&lt;FadeOut <em>duration</em>={5} <em>delay</em>={1}&gt;<br>  &lt;RedBox /&gt;<br>&lt;/FadeOut&gt;</pre><p>Here they are in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*BE0Ht_zW8ktLyv349BOrKg.gif" /><figcaption>Fade In Animation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*8ZNx7f9LXe_4t797UCRlvw.gif" /><figcaption>Fade Out Animation</figcaption></figure><p>It is fairly intuitive for the end-user to work out what props an animation component takes without looking at the documentation.</p><h3>Compositional animations</h3><p>Since these are just React components, we can compose them together to create chains of animations. For example, if we combine FadeIn with Zoom and FadeOut, we get an animation in which the red box will fade in, zoom, and then fade out.</p><pre>&lt;FadeIn <em>duration</em>={2} <em>delay</em>={0}&gt;<br>  &lt;Zoom <em>from</em>={1} <em>to</em>={2} <em>duration</em>={2} <em>delay</em>={2}&gt;<br>    &lt;FadeOut <em>duration</em>={2} <em>delay</em>={4}&gt;<br>      &lt;RedBox /&gt;<br>    &lt;/FadeOut&gt;<br>  &lt;/Zoom&gt;<br>&lt;/FadeIn&gt;</pre><p>Like all good code, this code tells a story that is eminently easy to read — fade in, then zoom, then fade out. Timing is co-ordinated through the duration and delay props. We could have all animations occurring simultaneously by setting all the delays to be 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*cp7dUE7UiEk8rlbVrYH6_Q.gif" /><figcaption>FadeIn, Zoom, FadeOut Animation</figcaption></figure><h3>Keeping track of transition animations</h3><p>Sometimes, keeping track of which animation to play can be difficult. Buttons can pop in when you initially launch the app, stay static for some time, bounce to remind you to tap on them, go back to the static state, so on. Using React props and state can quickly turn into a nested tree of if conditions that becomes very difficult to understand.</p><p>To solve this, we used a finite state machine library (<a href="https://xstate.js.org/">xstate</a>) to keep track of which states a component can be in, and the animations that link these states together. First, we define a state machine that lists the possible states, and assigns a different animation whenever a valid transition occurs.</p><pre>const buttonsMachine = Machine(<br>  {<br>    id: &quot;buttons&quot;,<br>    initial: &quot;hidden&quot;,<br>    context: { animation: Invisible },<br>    states: { /* ... states here ... */ },<br>  },<br>  {<br>    actions: {<br>      onShow: assign({ animation: (context) =&gt; PopIn }),<br>      onHide: assign({ animation: (context) =&gt; PopOut }),<br>      onUserIdle: assign({ animation: (context) =&gt; PopRemind }),<br>      onUserActive: assign({ animation: (context) =&gt; NoAnimation }),<br>    },<br>  }<br>);</pre><p>Then, we can use this state machine in combination with React props to decide which animation to play at a particular moment. If a React prop changes, then we attempt to transition into a different state, and if we succeed then the correct animation is applied.</p><pre>const CarouselButtons = ({ show, isIdle }) =&gt; {<br>  const [machine, send] = useMachine(buttonsMachine);</pre><pre>  useEffect(() =&gt; {<br>    send(show ? &quot;SHOW&quot; : &quot;HIDE&quot;);<br>    send(isIdle ? &quot;USER_IDLE&quot; : &quot;USER_ACTIVE&quot;);<br>  }, [show, isIdle]);</pre><pre>  const Animation = machine.context.animation;<br>  <br>  <em>return</em> (<br>    &lt;Animation&gt;<br>      &lt;Buttons /&gt;<br>    &lt;/Animation&gt;<br>  );<br>};</pre><p>This allows us to easily support transition animations between many possible states without making the code hard to understand.</p><h3>Animations in UAP CBeebies apps</h3><p>We have a host of different animations, but they all follow the same general principles — and they are all compositional, re-usable, flexible, and easy to use.</p><p>Let’s finish by looking at the animations used in anger inside a real app. Any of these image assets can be swapped out, any of the animations can be changed in their many degrees of freedom or replaced outright, just by changing one line of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*URDPptRHZHoEh_UxtBuVog.gif" /><figcaption>Playtime Island Intro Animation</figcaption></figure><p>And here is the code.</p><pre>import {<br>  Path,<br>  PopIn,<br>  BounceUp,<br>  Zoom,<br>  FadeOut,<br>} from &quot;@uap/animations&quot;;</pre><pre>...</pre><pre>const IntroAnimation = () =&gt; {</pre><pre>...</pre><pre>  return (<br>    &lt;FadeOut<br>      <em>shouldFade</em>={shouldFade}<br>      <em>onAnimationEnd</em>={() =&gt; animationIsFinished &amp;&amp; onFinish()} <br>    &gt;<br>      &lt;Zoom<br>        <em>onAnimationEnd</em>={() =&gt; {<br>          onFadeStart();<br>          setAnimationIsFinished(true);<br>        }}<br>        <em>onLoad</em>={() =&gt; setBackgroundLoaded(true)}<br>        <em>delay</em>={0}<br>        <em>duration</em>={8}<br>        <em>to</em>={1.3}<br>        <em>rotate</em>={5}<br>      &gt;<br>        &lt;BackgroundImage <em>{...backgroundImageProps} </em>/&gt;<br>      &lt;/Zoom&gt;<br>      {rightAnimationStarted &amp;&amp; (<br>        &lt;BackPath&gt;<br>          &lt;BackGlider <em>{...backgliderProps} </em>/&gt;<br>        &lt;/BackPath&gt;<br>      )}<br>      {foreGliderLoaded &amp;&amp; (<br>        &lt;CenteredPopIn <em>startingOpacity</em>={0.2} <em>duration</em>={0.6} <em>delay</em>={0}&gt;<br>          &lt;Logo <em>{...logoProps} </em>/&gt;<br>        &lt;/CenteredPopIn&gt;<br>      )}<br>      {logoLoaded &amp;&amp; (<br>        &lt;LeftBounce<br>          <em>rotateLeft</em>={true}<br>          <em>onAnimationIteration</em>={() =&gt; appIsLoaded &amp;&amp; setLeftPaused(true)}<br>        &gt;<br>          {!leftPaused &amp;&amp; (<br>            &lt;Bouncer <em>{...bouncerProps} </em>/&gt;<br>          )}<br>        &lt;/LeftBounce&gt;<br>      )}<br>      {leftPopLoaded &amp;&amp; (<br>        &lt;RightBounce<br>          <em>rotateRight</em>={true}<br>          <em>onAnimationIteration</em>={() =&gt; appIsLoaded &amp;&amp; setRightPaused(true)}<br>          <em>onAnimationStart</em>={() =&gt; setRightAnimationStarted(true)}<br>        &gt;<br>          {!rightPaused &amp;&amp; (<br>            &lt;Bouncer <em>{...bouncerProps} </em>/&gt;<br>          )}<br>        &lt;/RightBounce&gt;<br>      )}<br>      {backgroundLoaded &amp;&amp; (<br>        &lt;ForePath&gt;<br>          &lt;ForeGlider {...foregliderProps} /&gt;<br>        &lt;/ForePath&gt;<br>      )}<br>    &lt;/FadeOut&gt;<br>  )<br>}</pre><p>Hopefully, this has been an insightful blog about how we have created and put to use a declarative DSL to achieve composable and re-usable animations!</p><p>Stay tuned for more UAP-focused blog posts coming soon!</p><figure><img alt="Universal App Platform Logo" src="https://cdn-images-1.medium.com/max/200/1*1B35nOD7Fb7wa2S1VsXAZg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6ef582c033a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bbc-product-technology/css-animations-as-a-dom-based-animations-framework-d6ef582c033a">CSS Animations as a DOM-Based Animations Framework</a> was originally published in <a href="https://medium.com/bbc-product-technology">BBC Product &amp; Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a HTTP Proxy in Haskell on AWS Lambda]]></title>
            <link>https://medium.com/@iamchrisgrounds/build-a-http-proxy-in-haskell-on-aws-lambda-5cd8ab8cdde4?source=rss-8a5b6bbfbe01------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cd8ab8cdde4</guid>
            <category><![CDATA[haskell]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Chris Grounds]]></dc:creator>
            <pubDate>Sun, 05 May 2019 16:22:42 GMT</pubDate>
            <atom:updated>2019-05-05T16:22:42.156Z</atom:updated>
            <content:encoded><![CDATA[<p>This is just a quick one to put some Haskell code on AWS Lambda, and what’s better than a good-old HTTP Proxy?</p><h4>The Setup</h4><p>We’re going to use <a href="https://serverless.com/">serverless</a>, so let’s ensure we have that installed.</p><pre>npm install -g serverless</pre><p>And we’re going to use <a href="http://hackage.haskell.org/package/serverless-haskell">serverless-haskell</a> as our Haskell-Lambda library and <a href="https://docs.haskellstack.org/en/stable/README/">stack</a> as our build tool. So let’s install stack if we haven’t already:</p><pre>curl -sSL https://get.haskellstack.org/ | <strong>sh</strong></pre><p>and let’s create a project with serverless-haskell:</p><pre>stack new http-proxy-lambda https://raw.githubusercontent.com/seek-oss/serverless-haskell/master/serverless-haskell.hsfiles</pre><p>We’ve called our project <em>http-proxy-lambda</em> and we’ve used the serverless-haskell template to create the project. Now cd http-proxy-lambda.</p><h4>The Config</h4><p>Inside this project you’ll see a serverless.yml file, which is where we will configure our Lambda. We really want two things to be happening with this project. First, we want our Lambda to be proxying some resource, and we’ll write our Lambda handler in app/Main.hs, and second we want this endpoint to be publicly accessible through API Gateway. With serverless, that’s incredibly easy to express. In our serverless.yml file add:</p><pre>functions:  <br>  http-proxy-lambda:<br>    runtime: haskell    <br>    handler: http-proxy-lambda.http-proxy-lambda-exe<br>    events:     <br>     - http:        <br>        path: endpoint/{url}        <br>        method: get        <br>        cors: true</pre><p>There’s a couple things to note here. First is that we’ve moved runtime from the top-level to inside our specific function. This is because this provides us with the possibility of having multiple run-times for different functions at a later date — maybe we want a JS frontend?</p><p>The handler key is what tells serverless where to find the handler code. Specifically, http-proxy-lambda.http-proxy-lambda-exe says this is the http-proxy-lambda<em> project </em>(which we just created) and http-proxy-lambda-exe is the name of the executable. We can change the executable name by finding it in package.yaml and changing it there.</p><p>The events key is where we configure our API Gateway, setting up a HTTP GET request-response cycle when you hit endpoint/{url} — and we’ve turned CORS on, because why not?</p><h4>The Code</h4><p>Open app/Main.hs and replace the code already there with the following.</p><pre>{-# LANGUAGE OverloadedStrings #-} </pre><pre>module Main where </pre><pre>import           AWSLambda.Events.APIGateway<br>import           Control.Lens<br>import qualified Data.ByteString.Lazy.Internal as BSL<br>import qualified Data.HashMap.Strict as HMS<br>import           Data.Text<br>import qualified Data.Text.Lazy as LazyText<br>import qualified Data.Text.Lazy.Encoding as LazyText<br>import qualified Network.Wreq as Http</pre><pre>main :: IO ()<br>main = apiGatewayMain handler</pre><pre>htmlRes :: Int -&gt; Text -&gt; IO (APIGatewayProxyResponse Text)<br>htmlRes status proxyBody <br>  = pure $ htmlResWithNoBody status &amp; responseBody ?~ proxyBody  <br>  where    <br>    htmlResWithNoBody :: Int -&gt; APIGatewayProxyResponse Text<br>    htmlResWithNoBody statusCode <br>      = APIGatewayProxyResponse statusCode [(&quot;Content-Type&quot;, &quot;text/html&quot;)] Nothing</pre><pre>getProxyBody :: Http.Response BSL.ByteString -&gt; IO Text<br>getProxyBody resFromGivenUrl<br>  = return<br>  . LazyText.toStrict<br>  . LazyText.decodeUtf8<br>  $ resFromGivenUrl ^. Http.responseBody</pre><pre>handler :: APIGatewayProxyRequest Text -&gt; IO (APIGatewayProxyResponse Text)<br>handler request = do  <br>  let urlPath = HMS.lookup &quot;url&quot; $ request ^. agprqPathParameters   </pre><pre>  case urlPath of    <br>    Just path -&gt;      <br>      (Http.get $ &quot;https://&quot; &lt;&gt; unpack path)         <br>        &gt;&gt;= getProxyBody        <br>        &gt;&gt;= htmlRes 200    <br>    Nothing -&gt; htmlRes 500 &quot;No path found&quot;</pre><p>Because this will be compiled to an executable, we need to define a main function. And in this main function we set up what kind of Lambda handler we will be using — in this case, an apiGatewayMain handler.</p><p>The most important function after main is the handler function. And what it does is it takes the request and pulls off the path parameters. So if you visit endpoint/proxymeplease the request will contain a path hashmap of url: proxymeplease. This url key comes directly from the serverless.yml config we wrote earlier, when we wrote path: endpoint/{url}.</p><p>With this hashmap we lookup for the <em>url</em> key and if we find it we make a HTTP GET request to that endpoint. Once we’ve done that we pull out the response body with getProxyBody and then we form some HTML which we will return with htmlRes. If we don’t find a <em>url</em> key then we just return a 500 page.</p><p>What’s nice about this is that to return HTML, instead of the default JSON response Lambda would return, all we have to do is construct a APIGatewayProxyResponse and give it a <em>Content-Type</em> of <em>text/html</em>, as is done in the htmlRes function.</p><p>Note that the core sequence logic of our code is expressed in 3 lines here:</p><pre>(Http.get $ &quot;https://&quot; &lt;&gt; unpack path)         <br>  &gt;&gt;= getProxyBody        <br>  &gt;&gt;= htmlRes 200</pre><p>How clean and elegant.</p><p>With that we can deploy our Lambda + API Gateway with:</p><pre>sls deploy</pre><p>Providing we have an AWS account, of course. This will then give us a magical https://{bla}.execute-api-region.amazonaws.com/dev/endpoint/{url} endpoint.</p><h4>The Result</h4><p>And the proof is in the screenshots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*HeAMN6Qv7ZkA8ObYlw6qTA.png" /></figure><p>And since our AWS Lambda is sitting in the US (us-east-1), we can verify that we are proxying through US servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*DmArOXiNydSvtjItA6XP_w.png" /></figure><h4>Appendum</h4><p>Link to the full code here: <a href="https://github.com/chris-bacon/http-proxy-lambda">https://github.com/chris-bacon/http-proxy-lambda</a></p><p>Also note I’ve turned the Lambda off, which incidentally is done by simply running the command sls remove. Neat!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cd8ab8cdde4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Myth of Taxpayer Money]]></title>
            <link>https://medium.com/@iamchrisgrounds/the-myth-of-taxpayer-money-f90abdd3c5be?source=rss-8a5b6bbfbe01------2</link>
            <guid isPermaLink="false">https://medium.com/p/f90abdd3c5be</guid>
            <category><![CDATA[debt]]></category>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[taxes]]></category>
            <category><![CDATA[money]]></category>
            <category><![CDATA[mmt]]></category>
            <dc:creator><![CDATA[Chris Grounds]]></dc:creator>
            <pubDate>Sun, 10 Feb 2019 11:29:27 GMT</pubDate>
            <atom:updated>2019-02-10T11:29:27.942Z</atom:updated>
            <content:encoded><![CDATA[<p>We are told, time and time again, that the government should spend taxpayer money wisely, efficiently, and sustainably. The government is the custodian of the taxpayer’s money and should get good value for it. Often these pronouncements are followed by promises to use taxpayer money well by cutting government spending and making efficiency improvements. However, there is an unchallenged assumption here that does not stand up to scrutiny — namely, that there is such a thing as “taxpayer money.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AugQnSQsUWsWK3xR9SZUg.jpeg" /><figcaption>The Bank of England</figcaption></figure><p>Not only is there no such thing as taxpayer money, it is not the case, <em>ipso facto,</em> that the government <em>spends </em>taxpayer money. To see how this is so, let’s assume that taxpayer money <em>does </em>actually exist, and let’s assume that the government does spend it. As we shall see, these assumptions actually lead to a paradox.</p><p>In this alternative reality, where the government spends taxpayer money, the following situation holds. The government invokes a tax on the population — say, an income tax. This income tax takes money from the people who qualify and adds it to the Treasury account. The Treasury, then, takes that money and spends it on whatever the government wants to buy: a new hospital, school, submarine, or whatever.</p><p>Where does this money come from, assuming God does not randomly drop it from the sky? Well, it is “taxpayer” money. So the money, presumably, belongs to the taxpayers — therefore, it must come from them (i.e. the taxpayers must issue/print it). That is all well and good, but it does not represent this world. Taxpayers, in the UK, do not print pound sterling. That would, of course, be a criminal offense.</p><p>This creates the paradox: if taxpayers do not print “taxpayer money,” and the government needs to get “taxpayer money” before it can spend, then how can the government spend (where does it get the money from?) and how can taxpayers pay their taxes (where do they get the money from?)? This is an important point to mull over.</p><p>In order to tax someone, there must be something there to tax. Since taxpayers do not print their own money, there is nothing there to tax. And in order for the government to spend, the government must first tax. But since there is nothing there to tax, the government will never collect tax and so will never spend.</p><p>Clearly, this description is not one of <em>our </em>world. In our world, the government does spend, and taxpayers do pay their taxes. Something has to give — our initial assumptions must be wrong: there is no such thing as taxpayer money and governments do not require taxes to spend.</p><p>If we jettison the second assumption it turns out that the government must spend <em>before </em>it collects taxes. Thus, the act of spending creates new taxable money. This is because if it does not spend, then there will be nothing to collect — remember, taxpayers do not print their own money and it does not magically fall from the sky. Spending precedes taxation, by necessity. Now that we can see the money in circulation is government money — money issued by the government — it follows that taxpayers do not own it; so the first assumption is jettisoned. Therefore, the notion “taxpayer money” ceases to have any reality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f90abdd3c5be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compose For Speed]]></title>
            <link>https://medium.com/@iamchrisgrounds/compose-for-speed-b46a96c995a2?source=rss-8a5b6bbfbe01------2</link>
            <guid isPermaLink="false">https://medium.com/p/b46a96c995a2</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Chris Grounds]]></dc:creator>
            <pubDate>Wed, 16 May 2018 14:11:52 GMT</pubDate>
            <atom:updated>2018-05-16T14:11:52.235Z</atom:updated>
            <content:encoded><![CDATA[<p>A common functional pattern, for lack of a better word, is to compose various functions together. This is often seen as an elegant way of combining multiple operations on a single data structure. But another advantage of composition is that it allows us to write faster, more efficient code.</p><p>We’ll look briefly what composition is, some properties of map, and then consider some (contrived) examples in JavaScript along with their performances.</p><h4>Composition: What it is</h4><p>Very simply, composition is an operation that takes a function from <em>a</em> to <em>b</em>, and a function from <em>b </em>to c, and returns a function from <em>a </em>to <em>c</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1GXaZpYY7eXLd888X_MJUw.png" /></figure><p>The arrows are functions, <em>f</em> and <em>g</em>, and the circles are types. Here composition allows us to construct a new arrow starting at the first circle, <em>a</em>, ending at the last circle, <em>c. </em>What’s interesting here is that we don’t care about the arrows, nor do we care about the circles — so long as the end of one arrow matches with the beginning of another, we can compose the arrows.</p><h4>Chaining maps in JavaScript</h4><p>For the sake of argument, suppose we have an array with 100,000 numbers in it, called<em> nums. </em>And suppose we are interested in performing some elementary operations over each element in the array.</p><pre>const double = num =&gt; num * 2;<br>const triple = num =&gt; num * 3;<br>const quad = num =&gt; num * 4;<br>const exp = num =&gt; num * num;</pre><p>One way we might apply these functions to each element of the array would be to chain a series of maps together,</p><pre>nums<br> .map(double)<br> .map(triple)<br> .map(quad)<br> .map(exp);</pre><p>This maps <em>double</em> over nums, creating a new array, to which we map <em>triple</em> over, creating a new array, to which we map quad over… and so on. What’s important to notice here is that we are performing four mapping operations, which means we are building up three intermediate representations before returning our fourth array.</p><h4>An Important Property of <em>map</em></h4><p>Now, this is not ideal since the total number of maps, or passes over the array, is determined by the number of operations we want to perform, or O(<em>n</em>). A better solution would be one in which the number of passes over the array is just 1, or O(<em>1</em>). This can be achieved with function composition.</p><p>To see how we can achieve this with composition, consider the follow property of map:</p><pre>map <em>f</em> . map <em>g</em> = map (<em>f</em> . <em>g</em>)</pre><p>The dot (.) here is the composition operator, and <em>f</em> and <em>g</em> are functions. In English, this says,</p><pre>if you map f after mapping g, then that is the same as mapping a function which applies f after g.</pre><p>In other words, <em>a</em> <em>composition of maps is equal to a map of compositions</em>. Therefore, map is <em>distributive </em>over function composition. This is easy to verify (and a more rigorous proof of this can be found in Graham Hutton’s <a href="http://eprints.nottingham.ac.uk/224/1/fold.pdf"><em>Fold</em></a> paper).</p><pre><strong>Ex 1</strong>. (map (+10) . map (*2)) [1, 2, 3]<br>[12, 14, 16]</pre><pre><strong>Ex 2.</strong> map ((+10) . (*2)) [1, 2, 3]<br>[12, 14, 16]</pre><pre>(map (+10) . map (*2)) [1, 2, 3] == map ((+10) . (*2)) [1, 2, 3]<br>True</pre><p>Or the equivalent code in JavaScript, assuming we have a compose function,</p><pre><strong>Ex 1.</strong> [1, 2, 3].map(n =&gt; n * 2).map(n =&gt; n + 10)<br>[12, 14, 16]</pre><pre><strong>Ex 2.</strong> [1, 2, 3].map(compose(n =&gt; n + 10, n =&gt; n * 2))<br>[12, 14, 16]</pre><p>Despite returning the same values, the difference between<strong> Ex 1</strong> and <strong>Ex 2</strong> is the evaluation: the first example involves two passes (maps) over the array (once for the function (<em>*2</em>) and once for the function (<em>+10</em>)) — causing an intermediate representation to be created — whereas the second involves only one pass over the array —creating no intermediate representation.</p><h4>Performance in JavaScript: Some Examples</h4><p>So it follows that if we are able to compose our functions, we then can get away with performing only one map, which should be faster than multiple maps. In fact, this is something that the Haskell GHC compiler does as an optimisation, known as <em>fusion</em>. Of course, we do not have that luxury in JavaScript, therefore we will have to handcode the optimisation ourselves.</p><p>What happens in JavaScript in practice? In the following examples, we will use the <em>compose</em> function from the underscore library, along with the <em>console.time</em> and <em>console.timeEnd</em> functions to record time taken. We will compare what happens when you map a composed function with a series of chained maps.</p><p>In a file add the following (you’ll need to have installed underscore),</p><pre>const compose = require(‘underscore’).compose;</pre><pre>let nums = [];</pre><pre>for (let i = 0; i &lt; 100000; i++)<br> nums.push(i);</pre><pre>const double = num =&gt; num * 2;<br>const triple = num =&gt; num * 3;<br>const quad = num =&gt; num * 4;<br>const exp = num =&gt; num * num;</pre><pre>const composedFunction = compose(double, triple, quad, exp);</pre><pre>console.time(&quot;composed function&quot;);<br><strong>nums.map(composedFunction);</strong><br>console.timeEnd(&quot;composed function&quot;);</pre><pre>console.time(&quot;uncomposed function&quot;);<br><strong>nums<br> .map(double)<br> .map(triple)<br> .map(quad)<br> .map(exp);</strong><br>console.timeEnd(&quot;uncomposed function&quot;);</pre><p>The output of this (with a 2.9GHz i7 processor, using node 8), averaged over 10 runs[1]:</p><pre>$ node numberstest.js<br>composed function: 37.54ms<br>uncomposed function: 103.93ms</pre><p>That is, the version involving function composition is almost 3 times faster in this specific case. What about if we start mapping over arrays of objects? In another file add,</p><pre>const compose = require(‘underscore’).compose;</pre><pre>const doubleO = obj =&gt; ({ key: obj.key * 2 });<br>const tripleO = obj =&gt; ({ key: obj.key * 3 });<br>const quadO = obj =&gt; ({ key: obj.key * 4 });<br>const expO = obj =&gt; ({ key: obj.key * obj.key });</pre><pre>let os = [];</pre><pre>for (let i = 0; i &lt; 100000; i++)<br>    os.push({key: i})</pre><pre>const composedFunctionO = compose(doubleO, tripleO, quadO, expO);</pre><pre>console.time(&#39;composed function over objects&#39;);<br><strong>os.map(composedFunctionO);</strong><br>console.timeEnd(&#39;composed function over objects&#39;);</pre><pre>console.time(&#39;uncomposed function over objects&#39;);<br><strong>os<br> .map(doubleO)<br> .map(tripleO)<br> .map(quadO)<br> .map(expO);</strong><br>console.timeEnd(&#39;uncomposed function over objects&#39;);</pre><p>The output of this, averaged over 10 runs[2]:</p><pre>$ node objecttest.js<br>composed function over objects: 83.47ms<br>uncomposed function over objects: 176.50ms</pre><p>Again, composition wins by quite the mile. As a final example, consider the identity function,</p><pre>const id = x =&gt; x;</pre><p>This is probably one of the simplest functions writable — take an input and give it straight back without modification. Let’s look at what happens when we apply id to our array 10 times, just to be absurd.</p><pre>const compose = require(&#39;underscore&#39;).compose;</pre><pre>const id = obj =&gt; obj;</pre><pre>let os = [];</pre><pre>for (let i = 0; i &lt; 100000; i++)<br>    os.push({key: i})</pre><pre>const composedFunction = compose(id, id, id, id, id, id, id, id, id, id);</pre><pre>console.time(&#39;composed function of id&#39;);<br><strong>const r = os.map(composedFunction);</strong><br>console.timeEnd(&#39;composed function of id&#39;);</pre><pre>console.time(&#39;uncomposed function of id&#39;);<br><strong>os<br> .map(id)<br> .map(id)<br> .map(id)<br> .map(id)<br> .map(id)<br> .map(id)<br> .map(id)<br> .map(id)<br> .map(id)<br> .map(id);</strong><br>console.timeEnd(&#39;uncomposed function of id&#39;);</pre><p>The output of this, averaged over 10 runs[3]:</p><pre>$ node idtest.js<br>composed function of id: 40.57ms<br>uncomposed function of id: 261.12ms</pre><p>Again, composition is vastly faster, here around 6 times faster.</p><p>Now for the caveats. These examples are simple and really don’t reflect what programmers do in their day to day work. Moreover, the data structures we have used are relatively large and simple. However, the simplicity in the code will hopefully help to demonstrate the point — composition does not create intermediate representations, allowing a single map to be used, meaning faster code.</p><p>In itself that is an interesting result, but what makes this all the more significant is the fact that we arrived at this result purely by considering the abstract properties of our code. Namely, that map is distributive over function composition <em>— i.e. </em>map<em> f . </em>map<em> g = </em>map<em> </em>(<em>f . g</em>). We did not start with the code examples; instead, the code examples came out of these known mathematical properties.</p><h4>Appendix</h4><p>[1] Raw results for mapping over array of numbers:</p><pre>composed function: 36.411ms<br>uncomposed function: 101.838ms<br>composed function: 40.195ms<br>uncomposed function: 105.363ms<br>composed function: 39.725ms<br>uncomposed function: 109.773ms<br>composed function: 34.599ms<br>uncomposed function: 102.457ms<br>composed function: 38.232ms<br>uncomposed function: 107.059ms<br>composed function: 39.724ms<br>uncomposed function: 99.361ms<br>composed function: 36.200ms<br>uncomposed function: 103.650ms<br>composed function: 34.055ms<br>uncomposed function: 102.804ms<br>composed function: 35.248ms<br>uncomposed function: 100.624ms<br>composed function: 41.013ms<br>uncomposed function: 106.361ms</pre><p>[2] Raw results for mapping over array of simple objects:</p><pre>composed function over objects: 81.930ms<br>uncomposed function over objects: 183.875ms<br>composed function over objects: 82.504ms<br>uncomposed function over objects: 181.905ms<br>composed function over objects: 83.793ms<br>uncomposed function over objects: 182.160ms<br>composed function over objects: 84.268ms<br>uncomposed function over objects: 163.915ms<br>composed function over objects: 83.933ms<br>uncomposed function over objects: 179.896ms<br>composed function over objects: 83.308ms<br>uncomposed function over objects: 182.458ms<br>composed function over objects: 82.534ms<br>uncomposed function over objects: 181.936ms<br>composed function over objects: 82.354ms<br>uncomposed function over objects: 180.052ms<br>composed function over objects: 84.272ms<br>uncomposed function over objects: 165.253ms<br>composed function over objects: 85.831ms<br>uncomposed function over objects: 163.557ms</pre><p>[3] Raw results for mapping id over array of simple objects:</p><pre>composed function of id: 44.540ms<br>uncomposed function of id: 278.322ms<br>composed function of id: 40.849ms<br>uncomposed function of id: 280.103ms<br>composed function of id: 39.567ms<br>uncomposed function of id: 250.024ms<br>composed function of id: 40.501ms<br>uncomposed function of id: 258.685ms<br>composed function of id: 39.398ms<br>uncomposed function of id: 254.510ms<br>composed function of id: 40.280ms<br>uncomposed function of id: 266.085ms<br>composed function of id: 39.970ms<br>uncomposed function of id: 255.288ms<br>composed function of id: 40.891ms<br>uncomposed function of id: 252.170ms<br>composed function of id: 39.483ms<br>uncomposed function of id: 262.167ms<br>composed function of id: 40.250ms<br>uncomposed function of id: 253.815ms</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b46a96c995a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>