ploeh blog https://blog.ploeh.dk danish software design en-us Mark Seemann Mon, 20 May 2019 06:13:46 UTC Mon, 20 May 2019 06:13:46 UTC Maybe catamorphism https://blog.ploeh.dk/2019/05/20/maybe-catamorphism/ Mon, 20 May 2019 06:04:00 UTC <div id="post"> <p> <em>The catamorphism for Maybe is just a simplification of its fold.</em> </p> <p> This article is part of an <a href="/2019/04/29/catamorphisms">article series about catamorphisms</a>. A catamorphism is a <a href="/2017/10/04/from-design-patterns-to-category-theory">universal abstraction</a> that describes how to digest a data structure into a potentially more compact value. </p> <p> This article presents the catamorphism for <a href="/2018/03/26/the-maybe-functor">Maybe</a>, as well as how to identify it. The beginning of this article presents the catamorphism in C#, with examples. The rest of the article describes how to deduce the catamorphism. This part of the article presents my work in <a href="https://www.haskell.org">Haskell</a>. Readers not comfortable with Haskell can just read the first part, and consider the rest of the article as an optional appendix. </p> <p> <em>Maybe</em> is a <a href="https://bartoszmilewski.com/2014/01/14/functors-are-containers">data container</a> that models the absence or presence of a value. <a href="/2015/11/13/null-has-no-type-but-maybe-has">Contrary to null, Maybe has a type</a>, so offers a sane and reasonable way to model that situation. </p> <h3 id="1feeee3382ff44d182e0a28a33f8f80a"> C# catamorphism <a href="#1feeee3382ff44d182e0a28a33f8f80a" title="permalink">#</a> </h3> <p> This article uses <a href="/2018/06/04/church-encoded-maybe">Church-encoded Maybe</a>. Other, <a href="/2018/03/26/the-maybe-functor">alternative implementations of Maybe are possible</a>. The catamorphism for Maybe is the <code>Match</code> method: </p> <p> <pre><span style="color:#2b91af;">TResult</span>&nbsp;Match&lt;<span style="color:#2b91af;">TResult</span>&gt;(<span style="color:#2b91af;">TResult</span>&nbsp;nothing,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;just);</pre> </p> <p> Like the <a href="/2019/05/13/peano-catamorphism">Peano catamorphism</a>, the Maybe catamorphism is a pair of a value and a function. The <code>nothing</code> value corresponds to the absence of data, whereas the <code>just</code> function handles the presence of data. </p> <p> Given, for example, a Maybe containing a number, you can use <code>Match</code> to <a href="/2019/02/04/how-to-get-the-value-out-of-the-monad">get the value out of the Maybe</a>: </p> <p> <pre>&gt; <span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;maybe&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Just</span>&lt;<span style="color:blue;">int</span>&gt;(42); &gt; maybe.Match(0,&nbsp;x&nbsp;=&gt;&nbsp;x) 42 &gt; <span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;maybe&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Nothing</span>&lt;<span style="color:blue;">int</span>&gt;(); &gt; maybe.Match(0,&nbsp;x&nbsp;=&gt;&nbsp;x) 0</pre> </p> <p> The functionality is, however, more useful than a simple <em>get-value-or-default</em> operation. Often, you don't have a good default value for the type potentially wrapped in a Maybe object. In the core of your application architecture, it may not be clear how to deal with, say, the absence of a <code>Reservation</code> object, whereas at the boundary of your system, it's evident how to convert both absence and presence of data into a unifying type, such as an HTTP response: </p> <p> <pre><span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&nbsp;maybe&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:blue;">return</span>&nbsp;maybe &nbsp;&nbsp;&nbsp;&nbsp;.Select(r&nbsp;=&gt;&nbsp;Repository.Create(r)) &nbsp;&nbsp;&nbsp;&nbsp;.Match&lt;<span style="color:#2b91af;">IHttpActionResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nothing:&nbsp;Content( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">HttpStatusCode</span>.InternalServerError, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">HttpError</span>(<span style="color:#a31515;">&quot;Couldn&#39;t&nbsp;accept.&quot;</span>)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;just:&nbsp;id&nbsp;=&gt;&nbsp;Ok(id));</pre> </p> <p> This enables you to avoid special cases, such as null <code>Reservation</code> objects, or magic numbers like <code>-1</code> to indicate the absence of <code>id</code> values. At the boundary of an HTTP-based application, you know that you must return an HTTP response. That's the unifying type, so you can return <code>200 OK</code> with a reservation ID in the response body when data is present, and <code>500 Internal Server Error</code> when data is absent. </p> <h3 id="87d91da8944f4eb5b8b24e9ea20d3e1b"> Maybe F-Algebra <a href="#87d91da8944f4eb5b8b24e9ea20d3e1b" title="permalink">#</a> </h3> <p> As in the <a href="/2019/05/13/peano-catamorphism">previous article</a>, I'll use <code>Fix</code> and <code>cata</code> as explained in <a href="https://bartoszmilewski.com">Bartosz Milewski</a>'s excellent <a href="https://bartoszmilewski.com/2017/02/28/f-algebras/">article on F-Algebras</a>. </p> <p> While F-Algebras and fixed points are mostly used for recursive data structures, you can also define an F-Algebra for a non-recursive data structure. You already saw an example of that in the article about <a href="/2019/05/06/boolean-catamorphism">Boolean catamorphism</a>. The difference between Boolean values and Maybe is that the <em>just</em> case of Maybe carries a value. You can model this as a <code>Functor</code> with both a carrier type and a type argument for the data that Maybe may contain: </p> <p> <pre><span style="color:blue;">data</span>&nbsp;MaybeF&nbsp;a&nbsp;c&nbsp;=&nbsp;NothingF&nbsp;|&nbsp;JustF&nbsp;a&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#2b91af;">Show</span>,&nbsp;<span style="color:#2b91af;">Eq</span>,&nbsp;<span style="color:#2b91af;">Read</span>) <span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Functor</span>&nbsp;(<span style="color:blue;">MaybeF</span>&nbsp;a)&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;<span style="color:blue;">fmap</span>&nbsp;_&nbsp;&nbsp;NothingF&nbsp;=&nbsp;NothingF &nbsp;&nbsp;<span style="color:blue;">fmap</span>&nbsp;_&nbsp;(JustF&nbsp;x)&nbsp;=&nbsp;JustF&nbsp;x</pre> </p> <p> I chose to call the 'data type' <code>a</code> and the carrier type <code>c</code> (for <em>carrier</em>). As was also the case with <code>BoolF</code>, the <code>Functor</code> instance ignores the map function because the carrier type is missing from both the <code>NothingF</code> case and the <code>JustF</code> case. Like the <code>Functor</code> instance for <code>BoolF</code>, it'd seem that nothing happens, but at the type level, this is still a translation from <code>MaybeF a c</code> to <code>MaybeF a c1</code>. Not much of a function, perhaps, but definitely an <em>endofunctor</em>. </p> <p> In the previous articles, it was possible to work directly with the fixed points of both functors; i.e. <code>Fix BoolF</code> and <code>Fix NatF</code>. Haskell isn't happy about attempts to define various instances for <code>Fix (MaybeF a)</code>, so in order to make this easier, you can define a <code>newtype</code> wrapper: </p> <p> <pre><span style="color:blue;">newtype</span>&nbsp;MaybeFix&nbsp;a&nbsp;= &nbsp;&nbsp;MaybeFix&nbsp;{&nbsp;unMaybeFix&nbsp;::&nbsp;Fix&nbsp;(MaybeF&nbsp;a)&nbsp;}&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#2b91af;">Show</span>,&nbsp;<span style="color:#2b91af;">Eq</span>,&nbsp;<span style="color:#2b91af;">Read</span>)</pre> </p> <p> In order to make it easier to work with <code>MaybeFix</code> you can add helper functions to create values: </p> <p> <pre><span style="color:#2b91af;">nothingF</span>&nbsp;::&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;a nothingF&nbsp;=&nbsp;MaybeFix&nbsp;$&nbsp;Fix&nbsp;NothingF <span style="color:#2b91af;">justF</span>&nbsp;::&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;a justF&nbsp;=&nbsp;MaybeFix&nbsp;.&nbsp;Fix&nbsp;.&nbsp;JustF</pre> </p> <p> You can now create <code>MaybeFix</code> values to your heart's content: </p> <p> <pre>Prelude Fix Maybe&gt; justF 42 MaybeFix {unMaybeFix = Fix (JustF 42)} Prelude Fix Maybe&gt; nothingF MaybeFix {unMaybeFix = Fix NothingF}</pre> </p> <p> That's all you need to identify the catamorphism. </p> <h3 id="24db4c715d1f4540bd8f87604819952f"> Haskell catamorphism <a href="#24db4c715d1f4540bd8f87604819952f" title="permalink">#</a> </h3> <p> At this point, you have two out of three elements of an F-Algebra. You have an endofunctor (<code>MaybeF</code>), and an object <code>a</code>, but you still need to find a morphism <code>MaybeF a c -&gt; c</code>. Notice that the algebra you have to find is the function that reduces the functor to its <em>carrier type</em> <code>c</code>, not the 'data type' <code>a</code>. This takes some time to get used to, but that's how catamorphisms work. This doesn't mean, however, that you get to ignore <code>a</code>, as you'll see. </p> <p> As in the previous article, start by writing a function that will become the catamorphism, based on <code>cata</code>: </p> <p> <pre>maybeF&nbsp;=&nbsp;cata&nbsp;alg&nbsp;.&nbsp;unMaybeFix &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;alg&nbsp;&nbsp;NothingF&nbsp;=&nbsp;<span style="color:blue;">undefined</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;alg&nbsp;(JustF&nbsp;x)&nbsp;=&nbsp;<span style="color:blue;">undefined</span></pre> </p> <p> While this compiles, with its <code>undefined</code> implementations, it obviously doesn't do anything useful. I find, however, that it helps me think. How can you return a value of the type <code>c</code> from the <code>NothingF</code> case? You could pass an argument to the <code>maybeF</code> function: </p> <p> <pre>maybeF&nbsp;n&nbsp;=&nbsp;cata&nbsp;alg&nbsp;.&nbsp;unMaybeFix &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;alg&nbsp;&nbsp;NothingF&nbsp;=&nbsp;n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;alg&nbsp;(JustF&nbsp;x)&nbsp;=&nbsp;<span style="color:blue;">undefined</span></pre> </p> <p> The <code>JustF</code> case, contrary to <code>NothingF</code>, already contains a value, and it'd be incorrect to ignore it. On the other hand, <code>x</code> is a value of type <code>a</code>, and you need to return a value of type <code>c</code>. You'll need a function to perform the conversion, so pass such a function as an argument to <code>maybeF</code> as well: </p> <p> <pre><span style="color:#2b91af;">maybeF</span>&nbsp;::&nbsp;c&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;(a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;c)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;c maybeF&nbsp;n&nbsp;f&nbsp;=&nbsp;cata&nbsp;alg&nbsp;.&nbsp;unMaybeFix &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;alg&nbsp;&nbsp;NothingF&nbsp;=&nbsp;n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;alg&nbsp;(JustF&nbsp;x)&nbsp;=&nbsp;f&nbsp;x</pre> </p> <p> This works. Since <code>cata</code> has the type <code>Functor f =&gt; (f a -&gt; a) -&gt; Fix f -&gt; a</code>, that means that <code>alg</code> has the type <code>f a -&gt; a</code>. In the case of <code>MaybeF</code>, the compiler infers that the <code>alg</code> function has the type <code>MaybeF a c -&gt; c</code>, which is just what you need! </p> <p> You can now see what the carrier type <code>c</code> is for. It's the type that the algebra extracts, and thus the type that the catamorphism returns. </p> <p> Notice that <code>maybeF</code>, like the above C# <code>Match</code> method, takes as arguments a pair of a value and a function (together with the Maybe value itself). Those are two representations of the same idea. Furthermore, this is nearly identical to the <code>maybe</code> function in Haskell's <code>Data.Maybe</code> module. I found if fitting, therefore, to name the function <code>maybeF</code>. </p> <h3 id="d8a0eed800de48a994085c419b7b5379"> Basis <a href="#d8a0eed800de48a994085c419b7b5379" title="permalink">#</a> </h3> <p> You can implement most other useful functionality with <code>maybeF</code>. Here's the <code>Functor</code> instance: </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Functor</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;<span style="color:blue;">fmap</span>&nbsp;f&nbsp;=&nbsp;maybeF&nbsp;nothingF&nbsp;(justF&nbsp;.&nbsp;f)</pre> </p> <p> Since <code>fmap</code> should be a structure-preserving map, you'll have to map the <em>nothing</em> case to the <em>nothing</em> case, and <em>just</em> to <em>just</em>. When calling <code>maybeF</code>, you must supply a value for the <em>nothing</em> case and a function to deal with the <em>just</em> case. The <em>nothing</em> case is easy to handle: just use <code>nothingF</code>. </p> <p> In the <em>just</em> case, first apply the function <code>f</code> to map from <code>a</code> to <code>b</code>, and then use <code>justF</code> to wrap the <code>b</code> value in a new <code>MaybeFix</code> container to get <code>MaybeFix b</code>. </p> <p> <code>Applicative</code> is a little harder, but not much: </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Applicative</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;pure&nbsp;=&nbsp;justF &nbsp;&nbsp;f&nbsp;&lt;*&gt;&nbsp;x&nbsp;=&nbsp;maybeF&nbsp;nothingF&nbsp;(&lt;$&gt;&nbsp;x)&nbsp;f</pre> </p> <p> The <code>pure</code> function is just <em>justF</em> (pun intended). The <em>apply</em> operator <code>&lt;*&gt;</code> is more complex. </p> <p> Both <code>f</code> and <code>x</code> surrounding <code>&lt;*&gt;</code> are <code>MaybeFix</code> values: <code>f</code> is <code>MaybeFix (a -&gt; b)</code>, and <code>x</code> is <code>MaybeFix a</code>. While it's becoming increasingly clear that you can use a catamorphism like <code>maybeF</code> to implement most other functionality, to which <code>MaybeFix</code> value should you apply it? To <code>f</code> or <code>x</code>? </p> <p> Both are possible, but the code looks (in my opinion) more readable if you apply it to <code>f</code>. Again, when <code>f</code> is <em>nothing</em>, return <code>nothingF</code>. When <code>f</code> is <em>just</em>, use the functor instance to map <code>x</code> (using the infix <code>fmap</code> alias <code>&lt;$&gt;</code>). </p> <p> The <code>Monad</code> instance, on the other hand, is almost trivial: </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Monad</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;x&nbsp;&gt;&gt;=&nbsp;f&nbsp;=&nbsp;maybeF&nbsp;nothingF&nbsp;f&nbsp;x</pre> </p> <p> As usual, map <em>nothing</em> to <em>nothing</em> by supplying <code>nothingF</code>. <code>f</code> is already a function that returns a <code>MaybeFix b</code> value, so just use that. </p> <p> The <code>Foldable</code> instance is likewise trivial (although, as you'll see below, you can make it even more trivial): </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Foldable</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;foldMap&nbsp;=&nbsp;maybeF&nbsp;mempty</pre> </p> <p> The <code>foldMap</code> function must return a <code>Monoid</code> instance, so for the <em>nothing</em> case, simply return the identity, <em>mempty</em>. Furthermore, <code>foldMap</code> takes a function <code>a -&gt; m</code>, but since the <code>foldMap</code> implementation is <a href="https://en.wikipedia.org/wiki/Tacit_programming">point-free</a>, you can't 'see' that function as an argument. </p> <p> Finally, for the sake of completeness, here's the <code>Traversable</code> instance: </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Traversable</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;sequenceA&nbsp;=&nbsp;maybeF&nbsp;(pure&nbsp;nothingF)&nbsp;(justF&nbsp;&lt;$&gt;)</pre> </p> <p> In the <em>nothing</em> case, you can put <code>nothingF</code> into the desired <code>Applicative</code> with <code>pure</code>. In the <em>just</em> case you can take advantage of the desired <code>Applicative</code> being also a <code>Functor</code> by simply mapping the inner value(s) with <code>justF</code>. </p> <p> Since the <code>Applicative</code> instance for <code>MaybeFix</code> equals <code>pure</code> to <code>justF</code>, you could alternatively write the <code>Traversable</code> instance like this: </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Traversable</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;sequenceA&nbsp;=&nbsp;maybeF&nbsp;(pure&nbsp;nothingF)&nbsp;(pure&nbsp;&lt;$&gt;)</pre> </p> <p> I like this alternative less, since I find it confusing. The two appearances of <code>pure</code> relate to two different types. The <code>pure</code> in <code>pure nothingF</code> has the type <code>MaybeFix a -&gt; f (MaybeFix a)</code>, while the <code>pure</code> in <code>pure&nbsp;&lt;$&gt;</code> has the type <code>a -&gt; MaybeFix a</code>! </p> <p> Both implementations work the same, though: </p> <p> <pre>Prelude Fix Maybe&gt; sequenceA (justF ("foo", 42)) ("foo",MaybeFix {unMaybeFix = Fix (JustF 42)})</pre> </p> <p> Here, I'm using the <code>Applicative</code> instance of <code>(,) String</code>. </p> <p> Finally, you can implement conversions to and from the standard <code>Maybe</code> type, using <code>ana</code> as the dual of <code>cata</code>: </p> <p> <pre><span style="color:#2b91af;">toMaybe</span>&nbsp;::&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&nbsp;a toMaybe&nbsp;=&nbsp;maybeF&nbsp;Nothing&nbsp;<span style="color:blue;">return</span> <span style="color:#2b91af;">fromMaybe</span>&nbsp;::&nbsp;<span style="color:#2b91af;">Maybe</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;a fromMaybe&nbsp;=&nbsp;MaybeFix&nbsp;.&nbsp;ana&nbsp;coalg &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;coalg&nbsp;&nbsp;Nothing&nbsp;=&nbsp;NothingF &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;coalg&nbsp;(Just&nbsp;x)&nbsp;=&nbsp;JustF&nbsp;x</pre> </p> <p> This demonstrates that <code>MaybeFix</code> is isomorphic to <code>Maybe</code>, which again establishes that <code>maybeF</code> and <code>maybe</code> are equivalent. </p> <h3 id="2ec047e5122b4750a10cbe2012285524"> Alternatives <a href="#2ec047e5122b4750a10cbe2012285524" title="permalink">#</a> </h3> <p> As usual, the above <code>maybeF</code> isn't the only possible catamorphism. A trivial variation is to flip its arguments, but other variations exist. </p> <p> It's a recurring observation that a catamorphism is just a generalisation of a <em>fold</em>. In the above code, the <code>Foldable</code> instance already looked as simple as anyone could desire, but another variation of a catamorphism for Maybe is this gratuitously embellished definition: </p> <p> <pre><span style="color:#2b91af;">maybeF</span>&nbsp;::&nbsp;(a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;c&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;c)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;c&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;c maybeF&nbsp;f&nbsp;n&nbsp;=&nbsp;cata&nbsp;alg&nbsp;.&nbsp;unMaybeFix &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;alg&nbsp;&nbsp;NothingF&nbsp;=&nbsp;n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;alg&nbsp;(JustF&nbsp;x)&nbsp;=&nbsp;f&nbsp;x&nbsp;n</pre> </p> <p> This variation redundantly passes <code>n</code> as an argument to <code>f</code>, thereby changing the type of <code>f</code> to <code>a -&gt; c -&gt; c</code>. There's no particular motivation for doing this, apart from establishing that this catamorphism is exactly the same as the fold: </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Foldable</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;<span style="color:blue;">foldr</span>&nbsp;=&nbsp;maybeF</pre> </p> <p> You can still implement the other instances as well, but the rest of the code suffers in clarity. Here's a few examples: </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Functor</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;<span style="color:blue;">fmap</span>&nbsp;f&nbsp;=&nbsp;maybeF&nbsp;(<span style="color:blue;">const</span>&nbsp;.&nbsp;justF&nbsp;.&nbsp;f)&nbsp;nothingF <span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Applicative</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;pure&nbsp;=&nbsp;justF &nbsp;&nbsp;f&nbsp;&lt;*&gt;&nbsp;x&nbsp;=&nbsp;maybeF&nbsp;(<span style="color:blue;">const</span>&nbsp;.&nbsp;(&lt;$&gt;&nbsp;x))&nbsp;nothingF&nbsp;f <span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Monad</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;x&nbsp;&gt;&gt;=&nbsp;f&nbsp;=&nbsp;maybeF&nbsp;(<span style="color:blue;">const</span>&nbsp;.&nbsp;f)&nbsp;nothingF&nbsp;x</pre> </p> <p> I find that the need to compose with <code>const</code> does nothing to improve the readability of the code, so this variation is mostly, I think, of academic interest. It does show, though, that the catamorphism of Maybe is isomorphic to its fold, as the diagram in the overview article indicated: </p> <p> <img src="/content/binary/catamorphism-and-fold-relations.png" alt="Catamorphisms and folds as sets, for various sum types."> </p> <p> You can demonstrate that this variation, too, is isomorphic to <code>Maybe</code> with a set of conversion: </p> <p> <pre><span style="color:#2b91af;">toMaybe</span>&nbsp;::&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&nbsp;a toMaybe&nbsp;=&nbsp;maybeF&nbsp;(<span style="color:blue;">const</span>&nbsp;.&nbsp;<span style="color:blue;">return</span>)&nbsp;Nothing <span style="color:#2b91af;">fromMaybe</span>&nbsp;::&nbsp;<span style="color:#2b91af;">Maybe</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">MaybeFix</span>&nbsp;a fromMaybe&nbsp;=&nbsp;MaybeFix&nbsp;.&nbsp;ana&nbsp;coalg &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;coalg&nbsp;&nbsp;Nothing&nbsp;=&nbsp;NothingF &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;coalg&nbsp;(Just&nbsp;x)&nbsp;=&nbsp;JustF&nbsp;x</pre> </p> <p> Only <code>toMaybe</code> has changed, compared to above; the <code>fromMaybe</code> function remains the same. The only change to <code>toMaybe</code> is that the arguments have been flipped, and <code>return</code> is now composed with <code>const</code>. </p> <p> Since (according to <a href="http://amzn.to/13tGJ0f">Conceptual Mathematics</a>) isomorphisms are transitive this means that the two variations of <code>maybeF</code> are isomorphic. The latter, more complex, variation of <code>maybeF</code> is identical <code>foldr</code>, so we can consider the simpler, more frequently encountered variation a simplification of <em>fold</em>. </p> <h3 id="f88757d425a04e97956d89270b32c0c0"> Summary <a href="#f88757d425a04e97956d89270b32c0c0" title="permalink">#</a> </h3> <p> The catamorphism for Maybe is the same as its Church encoding: a pair made from a default value and a function. In Haskell's base library, this is simply called <code>maybe</code>. In the above C# code, it's called <code>Match</code>. </p> <p> This function is total, and you can implement any other functionality you need with it. I therefore consider it the canonical representation of Maybe, which is also why it annoys me that most Maybe implementations come equipped with partial functions like <code>fromJust</code>, or F#'s <code>Option.get</code>. Those functions shouldn't be part of a sane and reasonable Maybe API. You shouldn't need them. </p> <p> In this series of articles about catamorphisms, you've now seen the first example of catamorphism and fold coinciding. In the next article, you'll see another such example - probably the most well-known catamorphism example of them all. </p> <p> <strong>Next:</strong> List catamorphism. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2019/05/20/maybe-catamorphism Peano catamorphism https://blog.ploeh.dk/2019/05/13/peano-catamorphism/ Mon, 13 May 2019 05:10:00 UTC <div id="post"> <p> <em>The catamorphism for Peano numbers involves a base value and a successor function.</em> </p> <p> This article is part of an <a href="/2019/04/29/catamorphisms">article series about catamorphisms</a>. A catamorphism is a <a href="/2017/10/04/from-design-patterns-to-category-theory">universal abstraction</a> that describes how to digest a data structure into a potentially more compact value. </p> <p> This article presents the catamorphism for <a href="https://en.wikipedia.org/wiki/Natural_number">natural numbers</a>, as well as how to identify it. The beginning of the article presents the catamorphism in C#, with examples. The rest of the article describes how I deduced the catamorphism. This part of the article presents my work in <a href="https://www.haskell.org">Haskell</a>. Readers not comfortable with Haskell can just read the first part, and consider the rest of the article as an optional appendix. </p> <h3 id="742f4b9c0c014152a933961c10f98b66"> C# catamorphism <a href="#742f4b9c0c014152a933961c10f98b66" title="permalink">#</a> </h3> <p> In this article, I model natural numbers using <a href="https://en.wikipedia.org/wiki/Peano_axioms">Peano's model</a>, and I'll reuse the <a href="/2018/05/28/church-encoded-natural-numbers">Church-encoded implementation you've seen before</a>. The catamorphism for <code>INaturalNumber</code> is: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Cata&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;n,&nbsp;<span style="color:#2b91af;">T</span>&nbsp;zero,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;succ) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;n.Match(zero,&nbsp;p&nbsp;=&gt;&nbsp;p.Cata(succ(zero),&nbsp;succ)); }</pre> </p> <p> Notice that this is an extension method on <code>INaturalNumber</code>, taking two other arguments: a <code>zero</code> argument which will be returned when the number is <em>zero</em>, and a successor function to return the 'next' value based on a previous value. </p> <p> The <code>zero</code> argument is the easiest to understand. It's simply passed to <code>Match</code> so that this is the value that <code>Cata</code> returns when <code>n</code> is <em>zero</em>. </p> <p> The other argument to <code>Match</code> must be a <code>Func&lt;INaturalNumber, T&gt;</code>; that is, a function that takes an <code>INaturalNumber</code> as input and returns a value of the type <code>T</code>. You can supply such a function by using a lambda expression. This expression receives a predecessor <code>p</code> as input, and has to return a value of the type <code>T</code>. The only function available in this context, however, is <code>succ</code>, which has the type <code>Func&lt;T, T&gt;</code>. How can you make that work? </p> <p> As is often the case when programming with generics, it pays to <em>follow the types</em>. A <code>Func&lt;T, T&gt;</code> requires an input of the type <code>T</code>. Do you have any <code>T</code> objects around? </p> <p> The only available <code>T</code> object is <code>zero</code>, so you could call <code>succ(zero)</code> to produce another <code>T</code> value. While you could return that immediately, that'd ignore the predecessor <code>p</code>, so that's not going to work. Another option, which is the one that works, is to recursively call <code>Cata</code> with <code>succ(zero)</code> as the <code>zero</code> value, and <code>succ</code> as the second argument. </p> <p> What this accomplishes is that <code>Cata</code> keeps recursively calling itself until <code>n</code> is <em>zero</em>. The <code>zero</code> object, however, will be the result of repeated applications of <code>succ(zero)</code>. In other words, <code>succ</code> will be called as many times as the natural number. If <code>n</code> is 7, then <code>succ</code> will be called seven times, the first time with the original <code>zero</code> value, the next time with the result of <code>succ(zero)</code>, the third time with the result of <code>succ(succ(zero))</code>, and so on. If the number is 42, <code>succ</code> will be called 42 times. </p> <h3 id="633dae2048cd45ebaa17962710048c67"> Arithmetic <a href="#633dae2048cd45ebaa17962710048c67" title="permalink">#</a> </h3> <p> You can implement all the functionality you saw in the article on Church-encoded natural numbers. You can start gently by converting a Peano number into a normal C# <code>int</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">int</span>&nbsp;Count(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;n) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;n.Cata(0,&nbsp;x&nbsp;=&gt;&nbsp;1&nbsp;+&nbsp;x); }</pre> </p> <p> You can play with the functionality in <em>C# Interactive</em> to get a feel for how it works: </p> <p> <pre>&gt; <span style="color:#2b91af;">NaturalNumber</span>.Eight.Count() 8 &gt; <span style="color:#2b91af;">NaturalNumber</span>.Five.Count() 5</pre> </p> <p> The <code>Count</code> extension method uses <code>Cata</code> to count the level of recursion. The <code>zero</code> value is, not surprisingly, <code>0</code>, and the successor function simply adds one to the previous number. Since the successor function runs as many times as encoded by the Peano number, and since the initial value is <code>0</code>, you get the integer value of the number when <code>Cata</code> exits. </p> <p> A useful building block you can write using <code>Cata</code> is a function to increment a natural number by one: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;Increment(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;n) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;n.Cata(One,&nbsp;p&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Successor</span>(p)); }</pre> </p> <p> This, again, works as you'd expect: </p> <p> <pre>&gt; <span style="color:#2b91af;">NaturalNumber</span>.Zero.Increment().Count() 1 &gt; <span style="color:#2b91af;">NaturalNumber</span>.Eight.Increment().Count() 9</pre> </p> <p> With the <code>Increment</code> method and <code>Cata</code>, you can easily implement addition: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;Add(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;x,&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;x.Cata(y,&nbsp;p&nbsp;=&gt;&nbsp;p.Increment()); }</pre> </p> <p> The trick here is to use <code>y</code> as the <code>zero</code> case for <code>x</code>. In other words, if <code>x</code> is <em>zero</em>, then <code>Add</code> should return <code>y</code>. If <code>x</code> isn't <em>zero</em>, then <code>Increment</code> it as many times as the number encodes, but starting at <code>y</code>. In other words, start with <code>y</code> and <code>Increment</code> <code>x</code> times. </p> <p> The catamorphism makes it much easier to implement arithmetic operation. Just consider multiplication, which wasn't the simplest implementation in the previous article. Now, it's as simple as this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;Multiply(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;x,&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;x.Cata(Zero,&nbsp;p&nbsp;=&gt;&nbsp;p.Add(y)); }</pre> </p> <p> Start at <code>0</code> and simply <code>Add(y)</code> <code>x</code> times. </p> <p> <pre>&gt; <span style="color:#2b91af;">NaturalNumber</span>.Nine.Multiply(<span style="color:#2b91af;">NaturalNumber</span>.Four).Count() 36</pre> </p> <p> Finally, you can also implement some common predicates: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;IsZero(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;n) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;n.Cata&lt;<span style="color:#2b91af;">IChurchBoolean</span>&gt;(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>(),&nbsp;_&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>()); } <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;IsEven(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;n) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;n.Cata&lt;<span style="color:#2b91af;">IChurchBoolean</span>&gt;(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>(),&nbsp;b&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchNot</span>(b)); } <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;IsOdd(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;n) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchNot</span>(n.IsEven()); }</pre> </p> <p> Particularly <code>IsEven</code> is elegant: It considers <code>zero</code> even, so simply uses a <code>new ChurchTrue()</code> object for that case. In all other cases, it alternates between <em>false</em> and <em>true</em> by negating the predecessor. </p> <p> <pre>&gt; <span style="color:#2b91af;">NaturalNumber</span>.Three.IsEven().ToBool() false</pre> </p> <p> It seems convincing that we can use <code>Cata</code> to implement all the other functionality we need. That seems to be a characteristic of a catamorphism. Still, how do we know that <code>Cata</code> is, in fact, the catamorphism for natural numbers? </p> <h3 id="05dbca489b8a49be830df87e13bfcae3"> Peano F-Algebra <a href="#05dbca489b8a49be830df87e13bfcae3" title="permalink">#</a> </h3> <p> As in the <a href="/2019/05/06/boolean-catamorphism">previous article</a>, I'll use <code>Fix</code> and <code>cata</code> as explained in <a href="https://bartoszmilewski.com">Bartosz Milewski</a>'s excellent <a href="https://bartoszmilewski.com/2017/02/28/f-algebras/">article on F-Algebras</a>. The <code>NatF</code> type comes from his article as well: </p> <p> <pre><span style="color:blue;">data</span>&nbsp;NatF&nbsp;a&nbsp;=&nbsp;ZeroF&nbsp;|&nbsp;SuccF&nbsp;a&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#2b91af;">Show</span>,&nbsp;<span style="color:#2b91af;">Eq</span>,&nbsp;<span style="color:#2b91af;">Read</span>) <span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Functor</span>&nbsp;<span style="color:blue;">NatF</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;<span style="color:blue;">fmap</span>&nbsp;_&nbsp;ZeroF&nbsp;=&nbsp;ZeroF &nbsp;&nbsp;<span style="color:blue;">fmap</span>&nbsp;f&nbsp;(SuccF&nbsp;x)&nbsp;=&nbsp;SuccF&nbsp;$&nbsp;f&nbsp;x</pre> </p> <p> You can use the fixed point of this functor to define numbers with a shared type. Here's just the first ten: </p> <p> <pre><span style="color:#2b91af;">zeroF</span>,&nbsp;<span style="color:#2b91af;">oneF</span>,&nbsp;<span style="color:#2b91af;">twoF</span>,&nbsp;<span style="color:#2b91af;">threeF</span>,&nbsp;<span style="color:#2b91af;">fourF</span>,&nbsp;<span style="color:#2b91af;">fiveF</span>,&nbsp;<span style="color:#2b91af;">sixF</span>,&nbsp;<span style="color:#2b91af;">sevenF</span>,&nbsp;<span style="color:#2b91af;">eightF</span>,&nbsp;<span style="color:#2b91af;">nineF</span>&nbsp;::&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">NatF</span> zeroF&nbsp;&nbsp;=&nbsp;Fix&nbsp;ZeroF oneF&nbsp;&nbsp;&nbsp;=&nbsp;Fix&nbsp;$&nbsp;SuccF&nbsp;zeroF twoF&nbsp;&nbsp;&nbsp;=&nbsp;Fix&nbsp;$&nbsp;SuccF&nbsp;oneF threeF&nbsp;=&nbsp;Fix&nbsp;$&nbsp;SuccF&nbsp;twoF fourF&nbsp;&nbsp;=&nbsp;Fix&nbsp;$&nbsp;SuccF&nbsp;threeF fiveF&nbsp;&nbsp;=&nbsp;Fix&nbsp;$&nbsp;SuccF&nbsp;fourF sixF&nbsp;&nbsp;&nbsp;=&nbsp;Fix&nbsp;$&nbsp;SuccF&nbsp;fiveF sevenF&nbsp;=&nbsp;Fix&nbsp;$&nbsp;SuccF&nbsp;sixF eightF&nbsp;=&nbsp;Fix&nbsp;$&nbsp;SuccF&nbsp;sevenF nineF&nbsp;&nbsp;=&nbsp;Fix&nbsp;$&nbsp;SuccF&nbsp;eightF</pre> </p> <p> That's all you need to identify the catamorphism. </p> <h3 id="f0e66c873a034830a4b069229971299a"> Haskell catamorphism <a href="#f0e66c873a034830a4b069229971299a" title="permalink">#</a> </h3> <p> At this point, you have two out of three elements of an F-Algebra. You have an endofunctor (<code>NatF</code>), and an object <code>a</code>, but you still need to find a morphism <code>NatF a -&gt; a</code>. </p> <p> As in the previous article, start by writing a function that will become the catamorphism, based on <code>cata</code>: </p> <p> <pre>natF&nbsp;=&nbsp;cata&nbsp;alg &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;alg&nbsp;ZeroF&nbsp;=&nbsp;<span style="color:blue;">undefined</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;alg&nbsp;(SuccF&nbsp;predecessor)&nbsp;=&nbsp;<span style="color:blue;">undefined</span></pre> </p> <p> While this compiles, with its <code>undefined</code> implementations, it obviously doesn't do anything useful. I find, however, that it helps me think. How can you return a value of the type <code>a</code> from the <code>ZeroF</code> case? You could pass an argument to the <code>natF</code> function: </p> <p> <pre>natF&nbsp;z&nbsp;=&nbsp;cata&nbsp;alg &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;alg&nbsp;ZeroF&nbsp;=&nbsp;z &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;alg&nbsp;(SuccF&nbsp;predecessor)&nbsp;=&nbsp;<span style="color:blue;">undefined</span></pre> </p> <p> In the <code>SuccF</code> case, <code>predecessor</code> is already of the polymorphic type <code>a</code>, so instead of returning a constant value, you can supply a function as an argument to <code>natF</code> and use it in that case: </p> <p> <pre><span style="color:#2b91af;">natF</span>&nbsp;::&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;(a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">NatF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a natF&nbsp;z&nbsp;next&nbsp;=&nbsp;cata&nbsp;alg &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;alg&nbsp;ZeroF&nbsp;=&nbsp;z &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;alg&nbsp;(SuccF&nbsp;predecessor)&nbsp;=&nbsp;next&nbsp;predecessor</pre> </p> <p> This works. Since <code>cata</code> has the type <code>Functor f =&gt; (f a -&gt; a) -&gt; Fix f -&gt; a</code>, that means that <code>alg</code> has the type <code>f a -&gt; a</code>. In the case of <code>NatF</code>, the compiler infers that the <code>alg</code> function has the type <code>NatF a -&gt; a</code>, which is just what you need! </p> <p> For good measure, I should point out that, as usual, the above <code>natF</code> function isn't the only possible catamorphism. Trivially, you can flip the order of the arguments, and this would also be a catamorphism. These two alternatives are isomorphic. </p> <p> The <code>natF</code> function identifies the Peano number catamorphism, which is equivalent to the C# representation in the beginning of the article. I called the function <code>natF</code>, because there's a tendency in Haskell to name the 'case analysis' or catamorphism after the type, just with a lower-case initial letter. </p> <h3 id="e78ae79059e14f4b92f525393cc74861"> Basis <a href="#e78ae79059e14f4b92f525393cc74861" title="permalink">#</a> </h3> <p> A catamorphism can be used to implement most (if not all) other useful functionality, like all of the above C# functionality. In fact, I wrote the Haskell code first, and then translated my implementations into the above C# extension methods. This means that the following functions apply the same reasoning: </p> <p> <pre><span style="color:#2b91af;">evenF</span>&nbsp;::&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">NatF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">BoolF</span> evenF&nbsp;=&nbsp;natF&nbsp;trueF&nbsp;notF <span style="color:#2b91af;">oddF</span>&nbsp;::&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">NatF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">BoolF</span> oddF&nbsp;=&nbsp;notF&nbsp;.&nbsp;evenF <span style="color:#2b91af;">incF</span>&nbsp;::&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">NatF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">NatF</span> incF&nbsp;=&nbsp;natF&nbsp;oneF&nbsp;$&nbsp;Fix&nbsp;.&nbsp;SuccF <span style="color:#2b91af;">addF</span>&nbsp;::&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">NatF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">NatF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">NatF</span> addF&nbsp;x&nbsp;y&nbsp;=&nbsp;natF&nbsp;y&nbsp;incF&nbsp;x <span style="color:#2b91af;">multiplyF</span>&nbsp;::&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">NatF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">NatF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">NatF</span> multiplyF&nbsp;x&nbsp;y&nbsp;=&nbsp;natF&nbsp;zeroF&nbsp;(addF&nbsp;y)&nbsp;x</pre> </p> <p> Here are some GHCi usage examples: </p> <p> <pre>Prelude Boolean Nat&gt; evenF eightF Fix TrueF Prelude Boolean Nat&gt; toNum $ multiplyF sevenF sixF 42</pre> </p> <p> The <code>toNum</code> function corresponds to the above <code>Count</code> C# method. It is, again, based on <code>cata</code>. You can use <code>ana</code> to convert the other way: </p> <p> <pre><span style="color:#2b91af;">toNum</span>&nbsp;::&nbsp;<span style="color:blue;">Num</span>&nbsp;a&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">NatF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a toNum&nbsp;=&nbsp;natF&nbsp;0&nbsp;(+&nbsp;1) <span style="color:#2b91af;">fromNum</span>&nbsp;::&nbsp;(<span style="color:blue;">Eq</span>&nbsp;a,&nbsp;<span style="color:blue;">Num</span>&nbsp;a)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">NatF</span> fromNum&nbsp;=&nbsp;ana&nbsp;coalg &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;coalg&nbsp;0&nbsp;=&nbsp;ZeroF &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;coalg&nbsp;x&nbsp;=&nbsp;SuccF&nbsp;$&nbsp;x&nbsp;-&nbsp;1</pre> </p> <p> This demonstrates that <code>Fix NatF</code> is isomorphic to <code>Num</code> instances, such as <code>Integer</code>. </p> <h3 id="d09e79446af14875a42f66869e10f33a"> Summary <a href="#d09e79446af14875a42f66869e10f33a" title="permalink">#</a> </h3> <p> The catamorphism for Peano numbers is a pair consisting of a zero value and a successor function. The most common description of catamorphisms that I've found emphasise how a catamorphism is like a <em>fold;</em> an operation you can use to reduce a data structure like a list or a tree to a single value. This is what happens here, but even so, the <code>Fix NatF</code> type isn't a <code>Foldable</code> instance. The reason is that while <code>NatF</code> is a polymorphic type, its fixed point <code>Fix NatF</code> isn't. Haskell's <code>Foldable</code> type class requires foldable containers to be polymorphic (what C# programmers would call 'generic'). </p> <p> When I first ran into the concept of a <em>catamorphism</em>, it was invariably described as a 'generalisation of fold'. The examples shown were always how the catamorphism for linked list is the same as its <em>fold</em>. I found such explanations unhelpful, because I couldn't understand how those two concepts differ. </p> <p> The purpose with this article series is to show just how much more general the abstraction of a catamorphism is. In this article you saw how an infinitely recursive data structure like Peano numbers have a catamorphism, even though it isn't a parametrically polymorphic type. In the next article, though, you'll see the first example of a polymorphic type where the catamorphism coincides with the fold. </p> <p> <strong>Next:</strong> <a href="/2019/05/20/maybe-catamorphism">Maybe catamorphism</a>. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2019/05/13/peano-catamorphism Boolean catamorphism https://blog.ploeh.dk/2019/05/06/boolean-catamorphism/ Mon, 06 May 2019 12:30:00 UTC <div id="post"> <p> <em>The catamorphism for Boolean values is just the common ternary operator.</em> </p> <p> This article is part of an <a href="/2019/04/29/catamorphisms">article series about catamorphisms</a>. A catamorphism is a <a href="/2017/10/04/from-design-patterns-to-category-theory">universal abstraction</a> that describes how to digest a data structure into a potentially more compact value. </p> <p> This article presents the catamorphism for Boolean values, as well as how you identify it. The beginning of this article presents the catamorphism in C#, with a simple example. The rest of the article describes how I deduced the catamorphism. That part of the article presents my work in <a href="https://www.haskell.org">Haskell</a>. Readers not comfortable with Haskell can just read the first part, and consider the rest of the article as an optional appendix. </p> <h3 id="35155b758274445cbe57f75d730a4eb6"> C# catamorphism <a href="#35155b758274445cbe57f75d730a4eb6" title="permalink">#</a> </h3> <p> The catamorphism for Boolean values is the familiar <a href="https://en.wikipedia.org/wiki/%3F:">ternary conditional operator</a>: </p> <p> <pre>&gt; <span style="color:#2b91af;">DateTime</span>.Now.Day&nbsp;%&nbsp;2&nbsp;==&nbsp;0&nbsp;?&nbsp;<span style="color:#a31515;">&quot;Even&nbsp;date&quot;</span>&nbsp;:&nbsp;<span style="color:#a31515;">&quot;Odd&nbsp;date&quot;</span> "Odd date"</pre> </p> <p> Given a Boolean expression, you basically provide two values: one to use in case the Boolean expression is <em>true</em>, and one to use in case it's <em>false</em>. </p> <p> For <a href="/2018/05/24/church-encoded-boolean-values">Church-encoded Boolean values</a>, the catamorphism looks like this: </p> <p> <pre><span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">T</span>&nbsp;trueCase,&nbsp;<span style="color:#2b91af;">T</span>&nbsp;falseCase);</pre> </p> <p> This is an instance method where you must, again, supply two alternatives. When the instance represents <em>true</em>, you'll get the left-most value <code>trueCase</code>; otherwise, when the instance represents <em>false</em>, you'll get the right-most value <code>falseCase</code>. </p> <p> The catamorphism turns out to be the same as the <a href="/2018/05/22/church-encoding">Church encoding</a>. This seems to be a recurring pattern. </p> <h3 id="cd81cb92ed2d42f8bc0ad5adbde4b014"> Alternatives <a href="#cd81cb92ed2d42f8bc0ad5adbde4b014" title="permalink">#</a> </h3> <p> To be accurate, there's more than one catamorphism for Boolean values. It's only by convention that the value corresponding to <em>true</em> goes on the left, and the <em>false</em> value goes to the right. You could flip the arguments, and it would still be a catamorphism. This is, in fact, what Haskell's <code>Data.Bool</code> module does: </p> <p> <pre>Prelude Data.Bool&gt; bool "Odd date" "Even date" $ even date "Odd date"</pre> </p> <p> The <a href="http://hackage.haskell.org/package/base/docs/Data-Bool.html">module documentation</a> calls this the <em>"Case analysis for the <code>Bool</code> type"</em>, instead of a catamorphism, but the two representations are isomorphic: <blockquote> "This is equivalent to <code>if p then y else x</code>; that is, one can think of it as an if-then-else construct with its arguments reordered." </blockquote> This is another recurring result. There's typically more than one catamorphism, but the alternatives are isomorphic. In this article series, I'll mostly present the alternative that strikes me as the one you'll encounter most frequently. </p> <h3 id="60235fb428d14785a5aeea440c05cce5"> Fix <a href="#60235fb428d14785a5aeea440c05cce5" title="permalink">#</a> </h3> <p> In this and future articles, I'll derive the catamorphism from an F-Algebra. For an introduction to F-Algebras and fixed points, I'll refer you to <a href="https://bartoszmilewski.com">Bartosz Milewski</a>'s excellent <a href="https://bartoszmilewski.com/2017/02/28/f-algebras/">article on the topic</a>. In it, he presents a generic data type for a fixed point, as well as polymorphic functions for catamorphisms and anamorphisms. While they're available in his article, I'll repeat them here for good measure: </p> <p> <pre><span style="color:blue;">newtype</span>&nbsp;Fix&nbsp;f&nbsp;=&nbsp;Fix&nbsp;{&nbsp;unFix&nbsp;::&nbsp;f&nbsp;(Fix&nbsp;f)&nbsp;} <span style="color:#2b91af;">cata</span>&nbsp;::&nbsp;<span style="color:blue;">Functor</span>&nbsp;f&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;(f&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;f&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a cata&nbsp;alg&nbsp;=&nbsp;alg&nbsp;.&nbsp;<span style="color:blue;">fmap</span>&nbsp;(cata&nbsp;alg)&nbsp;.&nbsp;unFix <span style="color:#2b91af;">ana</span>&nbsp;::&nbsp;<span style="color:blue;">Functor</span>&nbsp;f&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;(a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;f&nbsp;a)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;f ana&nbsp;coalg&nbsp;=&nbsp;Fix&nbsp;.&nbsp;<span style="color:blue;">fmap</span>&nbsp;(ana&nbsp;coalg)&nbsp;.&nbsp;coalg</pre> </p> <p> This should be recognisable from Bartosz Milewski's article. With one small exception, this is just a copy of the code shown there. </p> <h3 id="6b0fdc2b04e540d19322f0e30c00e86c"> Boolean F-Algebra <a href="#6b0fdc2b04e540d19322f0e30c00e86c" title="permalink">#</a> </h3> <p> While F-Algebras and fixed points are mostly used for recursive data structures, you can also define an F-Algebra for a non-recursive data structure. As data types go, they don't get much simpler than Boolean values, which are just two mutually exclusive cases. In order to make a <code>Functor</code> out of the definition, though, you can equip it with a <em>carrier type:</em> </p> <p> <pre><span style="color:blue;">data</span>&nbsp;BoolF&nbsp;a&nbsp;=&nbsp;TrueF&nbsp;|&nbsp;FalseF&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#2b91af;">Show</span>,&nbsp;<span style="color:#2b91af;">Eq</span>,&nbsp;<span style="color:#2b91af;">Read</span>) <span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Functor</span>&nbsp;<span style="color:blue;">BoolF</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;<span style="color:blue;">fmap</span>&nbsp;_&nbsp;&nbsp;TrueF&nbsp;=&nbsp;&nbsp;TrueF &nbsp;&nbsp;<span style="color:blue;">fmap</span>&nbsp;_&nbsp;FalseF&nbsp;=&nbsp;FalseF</pre> </p> <p> The <code>Functor</code> instance simply ignores the carrier type and just returns <code>TrueF</code> and <code>FalseF</code>, respectively. It'd seem that nothing happens, but at the type level, this is still a translation from <code>BoolF a</code> to <code>BoolF b</code>. Not much of a function, perhaps, but definitely an <em>endofunctor</em>. </p> <p> Another note that may be in order here, as well as for all future articles in this series, is that you'll notice that most types and custom functions come with the <code>F</code> suffix. This is simply a suffix I've added to avoid conflicts with built-in types, values, and functions, such as <code>Bool</code>, <code>True</code>, <code>and</code>, and so on. The <code>F</code> is for <em>F-Algebra</em>. </p> <p> You can lift these values into <code>Fix</code> in order to make it fit with the <code>cata</code> function: </p> <p> <pre><span style="color:#2b91af;">trueF</span>,&nbsp;<span style="color:#2b91af;">falseF</span>&nbsp;::&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">BoolF</span> trueF&nbsp;&nbsp;=&nbsp;Fix&nbsp;&nbsp;TrueF falseF&nbsp;=&nbsp;Fix&nbsp;FalseF</pre> </p> <p> That's all you need to identify the catamorphism. </p> <h3 id="a28e972fc7eb45038427cff258c0c8f2"> Haskell catamorphism <a href="#a28e972fc7eb45038427cff258c0c8f2" title="permalink">#</a> </h3> <p> At this point, you have two out of three elements of an F-Algebra. You have an endofunctor (<code>BoolF</code>), and an object <code>a</code>, but you still need to find a morphism <code>BoolF a -&gt; a</code>. At first glance, this seems impossible, because neither <code>TrueF</code> nor <code>FalseF</code> actually contain a value of the type <code>a</code>. How, then, can you conjure an <code>a</code> value out of thin air? </p> <p> The <code>cata</code> function has the answer. </p> <p> What you can do is to start writing the function that will become the catamorphism, basing it on <code>cata</code>: </p> <p> <pre>boolF&nbsp;=&nbsp;cata&nbsp;alg &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;alg&nbsp;&nbsp;TrueF&nbsp;=&nbsp;<span style="color:blue;">undefined</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;alg&nbsp;FalseF&nbsp;=&nbsp;<span style="color:blue;">undefined</span></pre> </p> <p> While this compiles, with its <code>undefined</code> implementations, it obviously doesn't do anything useful. I find, however, that it helps me think. How can you return a value of the type <code>a</code> from the <code>TrueF</code> case? You could pass an argument to the <code>boolF</code> function: </p> <p> <pre>boolF&nbsp;x&nbsp;=&nbsp;cata&nbsp;alg &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;alg&nbsp;&nbsp;TrueF&nbsp;=&nbsp;x &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;alg&nbsp;FalseF&nbsp;=&nbsp;<span style="color:blue;">undefined</span></pre> </p> <p> That seems promising, so do that for the <code>FalseF</code> case as well: </p> <p> <pre><span style="color:#2b91af;">boolF</span>&nbsp;::&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">BoolF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a boolF&nbsp;x&nbsp;y&nbsp;=&nbsp;cata&nbsp;alg &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;alg&nbsp;&nbsp;TrueF&nbsp;=&nbsp;x &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;alg&nbsp;FalseF&nbsp;=&nbsp;y</pre> </p> <p> This works. Since <code>cata</code> has the type <code>Functor f =&gt; (f a -&gt; a) -&gt; Fix f -&gt; a</code>, that means that <code>alg</code> has the type <code>f a -&gt; a</code>. In the case of <code>BoolF</code>, the compiler infers that the <code>alg</code> function has the type <code>BoolF a -&gt; a</code>, which is just what you need! </p> <p> The <code>boolF</code> function identifies the Boolean catamorphism, which is equivalent to representations in the beginning of the article. I called the function <code>boolF</code>, because there's a tendency in Haskell to name the 'case analysis' or catamorphism after the type, just with a lower-case initial letter. </p> <p> You can use the <code>boolF</code> function just like the above ternary operator: </p> <p> <pre>Prelude Boolean Nat&gt; boolF "Even date" "Odd date" $ evenF dateF "Odd date"</pre> </p> <p> Here, I've also used <code>evenF</code> from the <code>Nat</code> module shown in the next article in the series. </p> <p> From the above definition of <code>boolF</code>, it should also be clear that you can arrive at the alternative catamorphism defined by <code>Data.Bool.bool</code> by simply flipping <code>x</code> and <code>y</code>. </p> <h3 id="54886f1be8684dd4a5909e4d50b7d5dc"> Basis <a href="#54886f1be8684dd4a5909e4d50b7d5dc" title="permalink">#</a> </h3> <p> A catamorphism can be used to implement most (if not all) other useful functionality. For Boolean values, that would be the standard Boolean operations <em>and</em>, <em>or</em>, and <em>not:</em> </p> <p> <pre><span style="color:#2b91af;">andF</span>&nbsp;::&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">BoolF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">BoolF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">BoolF</span> andF&nbsp;x&nbsp;y&nbsp;=&nbsp;boolF&nbsp;y&nbsp;falseF&nbsp;x <span style="color:#2b91af;">orF</span>&nbsp;::&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">BoolF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">BoolF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">BoolF</span> orF&nbsp;x&nbsp;y&nbsp;=&nbsp;boolF&nbsp;trueF&nbsp;y&nbsp;x <span style="color:#2b91af;">notF</span>&nbsp;::&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">BoolF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">BoolF</span> notF&nbsp;=&nbsp;boolF&nbsp;falseF&nbsp;trueF</pre> </p> <p> They work as you'd expect them to work: </p> <p> <pre>Prelude Boolean&gt; andF trueF falseF Fix FalseF Prelude Boolean&gt; orF trueF falseF Fix TrueF Prelude Boolean&gt; orF (notF trueF) falseF Fix FalseF</pre> </p> <p> You can also implement conversion to and from the built-in <code>Bool</code> type: </p> <p> <pre><span style="color:#2b91af;">toBool</span>&nbsp;::&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">BoolF</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">Bool</span> toBool&nbsp;=&nbsp;boolF&nbsp;True&nbsp;False <span style="color:#2b91af;">fromBool</span>&nbsp;::&nbsp;<span style="color:#2b91af;">Bool</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Fix</span>&nbsp;<span style="color:blue;">BoolF</span> fromBool&nbsp;=&nbsp;ana&nbsp;coalg &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;coalg&nbsp;&nbsp;True&nbsp;=&nbsp;TrueF &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;coalg&nbsp;False&nbsp;=&nbsp;FalseF</pre> </p> <p> This demonstrates that <code>Fix BoolF</code> is isomorphic to <code>Bool</code>. </p> <h3 id="327411e72cea46bbb1f6fe167738c7b2"> Summary <a href="#327411e72cea46bbb1f6fe167738c7b2" title="permalink">#</a> </h3> <p> The catamorphism for Boolean values is a function, method, or operator akin to the familiar ternary conditional operator. The most common descriptions of catamorphisms that I've found emphasise how a catamorphism is like a <em>fold;</em> an operation you can use to reduce a data structure like a list or a tree to a single value. In that light, it may be surprising that something as simple as Boolean values have an associated catamorphism. </p> <p> Since <code>Fix BoolF</code> is isomorphic to <code>Bool</code>, you may wonder what the point is. Why define this data type, and implement functions like <code>andF</code>, <code>orF</code>, and <code>notF</code>? </p> <p> The code presented here is nothing but an analysis tool. It's a way to identify the catamorphism for Boolean values. </p> <p> <strong>Next:</strong> <a href="/2019/05/13/peano-catamorphism">Peano catamorphism</a>. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2019/05/06/boolean-catamorphism Catamorphisms https://blog.ploeh.dk/2019/04/29/catamorphisms/ Mon, 29 Apr 2019 18:31:00 UTC <div id="post"> <p> <em>A catamorphism is a general abstraction that enables you to handle multiple values, for example in order to reduce them to a single value.</em> </p> <p> This article series is part of <a href="/2017/10/04/from-design-patterns-to-category-theory">an even larger series of articles about the relationship between design patterns and category theory</a>. In another article series in this big series of articles, you learned about <a href="/2018/03/19/functors-applicatives-and-friends">functors, applicatives, and other types of data containers</a>. </p> <p> You may have heard about <em>map-reduce</em> architectures. Much software can be designed around two general types of operations: those that <em>map</em> data, and those that <em>reduce</em> data. A <a href="https://bartoszmilewski.com/2014/01/14/functors-are-containers">functor is a container of data</a> that supports structure-preserving maps. Thus, you can think of <a href="/2018/03/22/functors">functors</a> as the general abstraction for map operations (also sometimes called <em>projections</em>). Does a similar universal abstraction exist for operations that reduce data? </p> <p> Yes, that abstraction is called a <em>catamorphism</em>. </p> <h3 id="bb64d005b16b49f892c00824ef803997"> Aggregation <a href="#bb64d005b16b49f892c00824ef803997" title="permalink">#</a> </h3> <p> <em>Catamorphism</em> is an intimidating word, so let's start with an example. You often have a collection of values that you'd like to reduce to a single value. Such a collection can contain arbitrarily complex objects, but I'll keep it simple and start with a collection of numbers: </p> <p> <pre><span style="color:blue;">new</span>[]&nbsp;{&nbsp;42,&nbsp;1337,&nbsp;2112,&nbsp;90125,&nbsp;5040,&nbsp;7,&nbsp;1984&nbsp;};</pre> </p> <p> This particular list of numbers is an array, but that's not important. What comes next works for any <code>IEnumerable&lt;T&gt;</code>, including arrays. I only chose an array because the C# syntax for array creation is more compact than for other collection types. </p> <p> How do you reduce those seven numbers to a single number? That depends on what you want that number to tell you. One option is to add the numbers together. There's a specific, built-in function for that: </p> <p> <pre>&gt; <span style="color:blue;">new</span>[]&nbsp;{&nbsp;42,&nbsp;1337,&nbsp;2112,&nbsp;90125,&nbsp;5040,&nbsp;7,&nbsp;1984&nbsp;}.Sum(); 100647</pre> </p> <p> The <a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sum">Sum</a> extension method is a one of many built-in functions that enable you to reduce a list of numbers to a single number: <a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.average">Average</a>, <a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.max">Max</a>, <a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.count">Count</a>, and so on. </p> <p> What do you do, though, if you need to reduce many values to one, and there's no existing function for that? What if, for example, you need to add all the numbers using <a href="/2018/07/16/angular-addition-monoid">modulo 360 addition</a>? </p> <p> In that case, you use <a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate">Aggregate</a>: </p> <p> <pre>&gt; <span style="color:blue;">new</span>[]&nbsp;{&nbsp;42,&nbsp;1337,&nbsp;2112,&nbsp;90125,&nbsp;5040,&nbsp;7,&nbsp;1984&nbsp;}.Aggregate((x,&nbsp;y)&nbsp;=&gt;&nbsp;(x&nbsp;+&nbsp;y)&nbsp;%&nbsp;360) 207</pre> </p> <p> The way to interpret this result is that the initial array represents a sequence of rotations (measured in degrees), and the result is the final angle after all the rotations have completed. </p> <p> In other (functional) languages, such a 'reduce' operation is called a <em>fold</em>. The metaphor, I suppose, is that you fold multiple values together, two by two. </p> <p> A <em>fold</em> is a catamorphism, but a catamorphism is a more general abstraction. For some data structures, the catamorphism is more powerful than the fold, but for collections, there's no difference. </p> <p> There's one edge case we need to be aware of, though. What if the collection is empty? </p> <h3 id="65483950f21d453ebe4e8949eac5751f"> Aggregation of empty containers <a href="#65483950f21d453ebe4e8949eac5751f" title="permalink">#</a> </h3> <p> What happens if you attempt to aggregate an empty collection? </p> <p> <pre>&gt; <span style="color:blue;">new</span>&nbsp;<span style="color:blue;">int</span>[0].Aggregate((x,&nbsp;y)&nbsp;=&gt;&nbsp;(x&nbsp;+&nbsp;y)&nbsp;%&nbsp;360) <span style="color:red;">Sequence contains no elements + System.Linq.Enumerable.Aggregate&lt;TSource&gt;(IEnumerable&lt;TSource&gt;, Func&lt;TSource, TSource, TSource&gt;)</span></pre> </p> <p> The <code>Aggregate</code> method throws an exception because it doesn't know how to deal with empty collections. The lambda expression you supply tells the <code>Aggregate</code> method how to combine two values into one. This is, for instance, how <a href="/2017/12/11/semigroups-accumulate">semigroups accumulate</a>. </p> <p> The lambda expression handles all cases where you have two or more values. If you have only a single value, then that's no problem either: </p> <p> <pre>&gt; <span style="color:blue;">new</span>[]&nbsp;{&nbsp;1337&nbsp;}.Aggregate((x,&nbsp;y)&nbsp;=&gt;&nbsp;(x&nbsp;+&nbsp;y)&nbsp;%&nbsp;360) 1337</pre> </p> <p> In that case, the lambda expression isn't involved at all, because the single value is simply returned without modification. In this example, this could even be interpreted as being incorrect, since you'd expect the result to be 257 (<code>1337 % 360</code>). </p> <p> It's safer to use the <code>Aggregate</code> overload that takes a <em>seed</em> value: </p> <p> <pre>&gt; <span style="color:blue;">new</span>&nbsp;<span style="color:blue;">int</span>[0].Aggregate(0,&nbsp;(x,&nbsp;y)&nbsp;=&gt;&nbsp;(x&nbsp;+&nbsp;y)&nbsp;%&nbsp;360) 0</pre> </p> <p> Not only does that gracefully handle empty collections, it also gives you a 'better' result for a single value: </p> <p> <pre>&gt; <span style="color:blue;">new</span>[]&nbsp;{&nbsp;1337&nbsp;}.Aggregate(0,&nbsp;(x,&nbsp;y)&nbsp;=&gt;&nbsp;(x&nbsp;+&nbsp;y)&nbsp;%&nbsp;360) 257</pre> </p> <p> This works better because the method always starts with the <em>seed</em> value, which means that even if there's only a single value (<code>1337</code>), the lambda expression still runs (<code>(0 + 1337) % 360</code>). </p> <p> This overload of <code>Aggregate</code> has a different type, though: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">TAccumulate</span>&nbsp;Aggregate&lt;<span style="color:#2b91af;">TSource</span>,&nbsp;<span style="color:#2b91af;">TAccumulate</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">TSource</span>&gt;&nbsp;source, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TAccumulate</span>&nbsp;seed, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">TAccumulate</span>,&nbsp;<span style="color:#2b91af;">TSource</span>,&nbsp;<span style="color:#2b91af;">TAccumulate</span>&gt;&nbsp;func);</pre> </p> <p> Notice that the <code>func</code> doesn't require the accumulator to have the same type as elements from the <code>source</code> collection. This enables you to translate on the fly, so to speak. You can still use binary operations like the above modulo 360 addition, because that just implies that both <code>TSource</code> and <code>TAccumulate</code> are <code>int</code>. </p> <p> With this overload, you could, for example, use <a href="/2018/07/16/angular-addition-monoid">the Angle class</a> to perform the work: </p> <p> <pre>&gt; <span style="color:blue;">new</span>[]&nbsp;{&nbsp;42,&nbsp;1337,&nbsp;2112,&nbsp;90125,&nbsp;5040,&nbsp;7,&nbsp;1984&nbsp;} . .Aggregate(<span style="color:#2b91af;">Angle</span>.Identity,&nbsp;(a,&nbsp;i)&nbsp;=&gt;&nbsp;a.Add(<span style="color:#2b91af;">Angle</span>.FromDegrees(i))) [{ Angle = 207° }]</pre> </p> <p> Now the <code>seed</code> argument is <code>Angle.Identity</code>, which implies that <code>TAccumulate</code> is <code>Angle</code>. The <code>source</code> is still a collection of numbers, so <code>TSource</code> is <code>int</code>. Hence, I called the angle <code>a</code> and the integer <code>i</code> in the lambda expression. The output is an <code>Angle</code> object that represents 207°. </p> <p> That <code>Aggregate</code> overload is the catamorphism for collections. It reduces a collection to an object. </p> <h3 id="5a964dee9b1f4cdd8427ce0a0806d65d"> Catamorphisms and folds <a href="#5a964dee9b1f4cdd8427ce0a0806d65d" title="permalink">#</a> </h3> <p> Is <em>catamorphism</em> just an intimidating word for <em>aggregate</em>, <em>accumulate</em>, <em>fold</em>, or <em>reduce?</em> </p> <p> It took me a long time to be able to tell the difference, because in many cases, it seems that there's no difference. The purpose of this article series is to make the distinction clearer. In short, a catamorphism is a more general concept. </p> <p> <img src="/content/binary/catamorphism-and-fold-relations.png" alt="Catamorphisms and folds as sets, for various sum types."> </p> <p> For some data structures, such as <a href="/2018/05/24/church-encoded-boolean-values">Boolean values</a>, or <a href="/2018/05/28/church-encoded-natural-numbers">Peano numbers</a>, the catamorphism is all there is; no fold exists. For other data structures, such as <a href="/2018/06/04/church-encoded-maybe">Maybe</a> or collections, the catamorphism and the fold coincide. Still other data structures, such as <a href="/2018/06/11/church-encoded-either">Either</a> and <a href="/2018/08/06/a-tree-functor">trees</a>, support folding, but the fold is based on the catamorphism. For those types, there are operations you can do with the catamorphism that are impossible to implement with the <em>fold</em> function. One example is that a tree's catamorphism enables you to count its leaves; you can't do that with its <em>fold</em> function. </p> <p> You'll see plenty of examples in this article series: </p> <p> <ul> <li><a href="/2019/05/06/boolean-catamorphism">Boolean catamorphism</a></li> <li><a href="/2019/05/13/peano-catamorphism">Peano catamorphism</a></li> <li><a href="/2019/05/20/maybe-catamorphism">Maybe catamorphism</a></li> <li>List catamorphism</li> <li>Either catamorphism</li> <li>Tree catamorphism</li> <li>Full binary tree catamorphism</li> <li>Payment types catamorphism</li> </ul> </p> <p> Each of these articles will contain a fair amount of <a href="https://www.haskell.org">Haskell</a> code, but even if you're an object-oriented programmer who doesn't read Haskell, you should still scan them, as I'll start each with some C# examples. The Haskell code, by the way, is <a href="https://github.com/ploeh/FAlgebras">available on GitHub</a>. </p> <h3 id="cc687d1bebed47229cbdeffdf98fd666"> Greek <a href="#cc687d1bebed47229cbdeffdf98fd666" title="permalink">#</a> </h3> <p> When encountering a word like <em>catamorphism</em>, your reaction might be: <blockquote> "Catamorphism?! What does that even mean? It's all Greek to me." </blockquote> Indeed, it's Greek, as is so much of mathematical terminology. The <em>cata</em> prefix means 'down'; lots of words start with <em>cata</em>, like <em>catastrophe</em>, <em>catalogue</em>, <em>catatonia</em>, <em>catacomb</em>, etc. </p> <p> The <em>morph</em> suffix generally means 'shape'. While the <em>cata</em> prefix appears in common words like <em>catastrophe</em>, the <em>morph</em> suffix mostly appears in more academic contexts. Programmers will probably have encountered <em>polymorphism</em> and <em>skeuomorphism</em>, not to mention <a href="/2018/01/08/software-design-isomorphisms">isomorphism</a>. While <em>morphism</em> is heavily used in mathematics, other sciences use the suffix too, like <em>dimorphism</em> in biology. </p> <p> In category theory, a <em>morphism</em> is basically just an arrow that points from one object to another. Think of it as a function. </p> <p> If a morphism is just a function, why don't we just call it that, then? Is it really necessary with this intimidating terminology? Yes and no. </p> <p> If someone had originally figured all of this out in the context of mainstream programming, he or she would probably have used friendlier names, like <em>condense</em>, <em>reduce</em>, <em>fold</em>, and so on. This would have been more encouraging, although <a href="/2017/10/05/monoids-semigroups-and-friends">I'm not sure it would have been better</a>. </p> <p> In software architecture we use many overloaded terms. For example, what's a <em>service</em>, or a <em>client?</em> What does <em>tier</em> mean? Is it the same as a <em>layer</em>, or is it something different? What's the <a href="http://tomasp.net/blog/2015/library-frameworks">difference between a library and a framework</a>? </p> <p> At least a word like <em>catamorphism</em> is concise. It's not in common use, so isn't overloaded and vague. </p> <p> Another, more pragmatic, concern is that whether you like it or not, the terminology is already established. Mathematicians decided to name the concept <em>catamorphism</em>. While the name may seem intimidating, I prefer to teach concepts like these using established terminology. This means that if my articles are unclear, you can do further research with other resources. That's the benefit of established terminology, whether you like the specific words or not. </p> <h3 id="c179dad7693c48c2ae592d33cb2be792"> Summary <a href="#c179dad7693c48c2ae592d33cb2be792" title="permalink">#</a> </h3> <p> You can compose entire applications based on the abstractions of <em>map</em> and <em>reduce</em>. You can see one example of such a system in my <a href="https://blog.ploeh.dk/functional-architecture-with-fsharp">A Functional Architecture with F#</a> Pluralsight course. </p> <p> The terms <em>map</em> and <em>reduce</em> may, however, not be helpful, because it may not be clear exactly what types of data you can map, and what types you can reduce. One of the most important goals of this overall article series about universal abstractions is to help you identify when such software architectures apply. This is more often that you think. </p> <p> What sort of data can you map? You can map <em>functors</em>. While hardly finite, there's a catalogue of well-known functors, of which I've covered some, but not all. That catalogue contains data containers like <a href="/2018/03/26/the-maybe-functor">Maybe</a>, <a href="/2018/08/06/a-tree-functor">Tree</a>, <a href="/2018/09/10/the-lazy-functor">lazy computations</a>, <a href="/2018/09/24/asynchronous-functors">tasks</a>, and perhaps a score more. The catalogue of (actually useful) functors has, in my experience, a manageable size. </p> <p> Likewise you could ask: What sort of data can you reduce? How do you implement that reduction? Again, there's a compact set of well-known catamorphisms. How do you reduce a collection? You use its catamorphism (which is equal to a fold). How do you reduce a tree? You use its catamorphism. How do you reduce an Either object? You use its catamorphism. </p> <p> When we learn new programming languages, new libraries, new frameworks, we gladly invest time in learning hundreds, if not thousands, of keywords, APIs, extensibility points, and so on. May I offer, for your consideration, that your mental resources are better spent learning only a handful of universal abstractions? </p> <p> <strong>Next:</strong> <a href="/2019/05/06/boolean-catamorphism">Boolean catamorphism</a>. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2019/04/29/catamorphisms Applicative monoids https://blog.ploeh.dk/2019/04/22/applicative-monoids/ Mon, 22 Apr 2019 05:36:00 UTC <div id="post"> <p> <em>An applicative functor containing monoidal values itself forms a monoid.</em> </p> <p> This article is an instalment in <a href="/2018/10/01/applicative-functors">an article series about applicative functors</a>. An applicative functor is a <a href="https://bartoszmilewski.com/2014/01/14/functors-are-containers">data container</a> that supports combinations. If an applicative functor contains values of a type that gives rise to a <a href="/2017/10/06/monoids">monoid</a>, then the <a href="/2018/03/22/functors">functor</a> itself forms a monoid. </p> <p> In a previous article you learned that <a href="/2019/04/15/lazy-monoids">lazy computations of monoids remain monoids</a>. Furthermore, <a href="/2018/12/17/the-lazy-applicative-functor">a lazy computation is an applicative functor</a>, and it turns out that the result generalises. The result regarding lazy computation is just a special case. </p> <h3 id="3c6acb0da15b4ae8b78f5d8879b7efe3"> Monap <a href="#3c6acb0da15b4ae8b78f5d8879b7efe3" title="permalink">#</a> </h3> <p> Since version 4.11 of <a href="https://www.haskell.org">Haskell</a>'s <em>base</em> library, <code>Monoid</code> is a subset of <code>Semigroup</code>, so in order to create a <code>Monoid</code> instance, you must first define a <code>Semigroup</code> instance. </p> <p> In order to escape the need for flexible contexts, you'll have to define a wrapper <code>newtype</code> that'll be the instance. What should you call it? It's going to be an applicative functor of monoids, so perhaps something like <em>ApplicativeMonoid?</em> Nah, that's too long. <em>AppMon</em>, then? Sure, but how about flipping the terms: <em>MonApp?</em> That's better. Let's drop the last <em>p</em> and dispense with the <a href="https://en.wikipedia.org/wiki/Camel_case">Pascal case</a>: <em>Monap</em>. </p> <p> <em>Monap</em> almost looks like <em>Monad</em>, only with the last letter rotated half a revolution. This should allow for maximum confusion. </p> <p> To be clear, I normally don't advocate for droll word play when writing production code, but I occasionally do it in articles and presentations. The <em>Monap</em> in this article exists only to illustrate a point. It's not intended to be used. Furthermore, this article doesn't discuss monads at all, so the risk of confusion should, hopefully, be minimised. I may, however, regret this decision... </p> <h3 id="fb2568655a314bba8e417d06317b2690"> Applicative semigroup <a href="#fb2568655a314bba8e417d06317b2690" title="permalink">#</a> </h3> <p> First, introduce the wrapper <code>newtype</code>: </p> <p> <pre><span style="color:blue;">newtype</span>&nbsp;Monap&nbsp;f&nbsp;a&nbsp;=&nbsp;Monap&nbsp;{&nbsp;runMonap&nbsp;::&nbsp;f&nbsp;a&nbsp;}&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#2b91af;">Show</span>,&nbsp;<span style="color:#2b91af;">Eq</span>)</pre> </p> <p> This only states that there's a type called <code>Monap</code> that wraps some higher-kinded type <code>f a</code>; that is, a container <code>f</code> of values of the type <code>a</code>. The intent is that <code>f</code> is an applicative functor, hence the use of the letter <em>f</em>, but the type itself doesn't constrain <code>f</code> to any type class. </p> <p> The <code>Semigroup</code> instance does, though: </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;(<span style="color:blue;">Applicative</span>&nbsp;f,&nbsp;<span style="color:blue;">Semigroup</span>&nbsp;a)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;<span style="color:blue;">Semigroup</span>&nbsp;(<span style="color:blue;">Monap</span>&nbsp;f&nbsp;a)&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;(Monap&nbsp;x)&nbsp;&lt;&gt;&nbsp;(Monap&nbsp;y)&nbsp;=&nbsp;Monap&nbsp;$&nbsp;liftA2&nbsp;<span style="color:#2b91af;">(&lt;&gt;)</span>&nbsp;x&nbsp;y </pre> </p> <p> This states that when <code>f</code> is a <code>Applicative</code> instance, and <code>a</code> is a <code>Semigroup</code> instance, then <code>Monap f a</code> is also a <code>Semigroup</code> instance. </p> <p> Here's an example of combining two applicative <a href="/2017/11/27/semigroups">semigroups</a>: </p> <p> <pre>λ&gt; Monap (Just (Max 42)) &lt;&gt; Monap (Just (Max 1337)) Monap {runMonap = Just (Max {getMax = 1337})}</pre> </p> <p> This example uses the <code>Max</code> semigroup container, and <code>Maybe</code> as the applicative functor. For <code>Max</code>, the <code>&lt;&gt;</code> operator returns the value that contains the highest value, which in this case is 1337. </p> <p> It even works when the applicative functor in question is <code>IO</code>: </p> <p> <pre>λ&gt; runMonap $ Monap (Sum &lt;$&gt; randomIO @Word8) &lt;&gt; Monap (Sum &lt;$&gt; randomIO @Word8) Sum {getSum = 165}</pre> </p> <p> This example uses <code>randomIO</code> to generate two random values. It uses the <code>TypeApplications</code> GHC extension to make <code>randomIO</code> generate <code>Word8</code> values. Each random number is projected into the <code>Sum</code> container, which means that <code>&lt;&gt;</code> will add the numbers together. In the above example, the result is 165, but if you evaluate the expression a second time, you'll most likely get another result: </p> <p> <pre>λ&gt; runMonap $ Monap (Sum &lt;$&gt; randomIO @Word8) &lt;&gt; Monap (Sum &lt;$&gt; randomIO @Word8) Sum {getSum = 246}</pre> </p> <p> You can also use linked list (<code>[]</code>) as the applicative functor. In this case, the result may be surprising (depending on what you expect): </p> <p> <pre>λ&gt; Monap [Product 2, Product 3] &lt;&gt; Monap [Product 4, Product 5, Product 6] Monap {runMonap = [Product {getProduct = 8},Product {getProduct = 10},Product {getProduct = 12}, Product {getProduct = 12},Product {getProduct = 15},Product {getProduct = 18}]}</pre> </p> <p> Notice that we get all the combinations of products: <em>2</em> multiplied with each element in the second list, followed by <em>3</em> multiplied by each of the elements in the second list. This shouldn't be that startling, though, since you've already, previously in this article series, seen several examples of how an applicative functor implies combinations. </p> <h3 id="33d4ff4f0fbf4e3cbf4d802b0f287f63"> Applicative monoid <a href="#33d4ff4f0fbf4e3cbf4d802b0f287f63" title="permalink">#</a> </h3> <p> With the <code>Semigroup</code> instance in place, you can now add the <code>Monoid</code> instance: </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;(<span style="color:blue;">Applicative</span>&nbsp;f,&nbsp;<span style="color:blue;">Monoid</span>&nbsp;a)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;<span style="color:blue;">Monoid</span>&nbsp;(<span style="color:blue;">Monap</span>&nbsp;f&nbsp;a)&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;mempty&nbsp;=&nbsp;Monap&nbsp;$&nbsp;pure&nbsp;$&nbsp;mempty </pre> </p> <p> This is straightforward: you take the identity (<code>mempty</code>) of the monoid <code>a</code>, promote it to the applicative functor <code>f</code> with <code>pure</code>, and finally put that value into the <code>Monap</code> wrapper. </p> <p> This works fine as well: </p> <p> <pre>λ&gt; mempty :: Monap Maybe (Sum Integer) Monap {runMonap = Just (Sum {getSum = 0})} λ&gt; mempty :: Monap [] (Product Word8) Monap {runMonap = [Product {getProduct = 1}]}</pre> </p> <p> The identity laws also seem to hold: </p> <p> <pre>λ&gt; Monap (Right mempty) &lt;&gt; Monap (Right (Sum 2112)) Monap {runMonap = Right (Sum {getSum = 2112})} λ&gt; Monap ("foo", All False) &lt;&gt; Monap mempty Monap {runMonap = ("foo",All {getAll = False})}</pre> </p> <p> The last, right-identity example is interesting, because the applicative functor in question is a tuple. Tuples are <code>Applicative</code> instances when the first, or left, element is a <code>Monoid</code> instance. In other words, <code>f</code> is, in this case, <code>(,) String</code>. The <code>Monoid</code> instance that <code>Monap</code> sees as <code>a</code>, on the other hand, is <code>All</code>. </p> <p> Since <a href="/2017/10/30/tuple-monoids">tuples of monoids are themselves monoids</a>, however, I can get away with writing <code>Monap mempty</code> on the right-hand side, instead of the more elaborate template the other examples use: </p> <p> <pre>λ&gt; Monap ("foo", All False) &lt;&gt; Monap ("", mempty) Monap {runMonap = ("foo",All {getAll = False})}</pre> </p> <p> or perhaps even: </p> <p> <pre>λ&gt; Monap ("foo", All False) &lt;&gt; Monap (mempty, mempty) Monap {runMonap = ("foo",All {getAll = False})}</pre> </p> <p> Ultimately, all three alternatives mean the same. </p> <h3 id="6b484b60d19b4ef4a3716ceaa693cb8b"> Associativity <a href="#6b484b60d19b4ef4a3716ceaa693cb8b" title="permalink">#</a> </h3> <p> As usual, I'm not going to do the work of formally proving that the monoid laws hold for the <code>Monap</code> instances, but I'd like to share some QuickCheck properties that indicate that they do, starting with a property that verifies associativity: </p> <p> <pre><span style="color:#2b91af;">assocLaw</span>&nbsp;::&nbsp;(<span style="color:blue;">Eq</span>&nbsp;a,&nbsp;<span style="color:blue;">Show</span>&nbsp;a,&nbsp;<span style="color:blue;">Semigroup</span>&nbsp;a)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Property</span> assocLaw&nbsp;x&nbsp;y&nbsp;z&nbsp;=&nbsp;(x&nbsp;&lt;&gt;&nbsp;y)&nbsp;&lt;&gt;&nbsp;z&nbsp;===&nbsp;x&nbsp;&lt;&gt;&nbsp;(y&nbsp;&lt;&gt;&nbsp;z)</pre> </p> <p> This property is entirely generic. It'll verify associativity for any <code>Semigroup a</code>, not only for <code>Monap</code>. You can, however, run it for various <code>Monap</code> types, as well. You'll see how this is done a little later. </p> <h3 id="51973eba155f418e8903d37f6d3938d2"> Identity <a href="#51973eba155f418e8903d37f6d3938d2" title="permalink">#</a> </h3> <p> Likewise, you can write two properties that check left and right identity, respectively. </p> <p> <pre><span style="color:#2b91af;">leftIdLaw</span>&nbsp;::&nbsp;(<span style="color:blue;">Eq</span>&nbsp;a,&nbsp;<span style="color:blue;">Show</span>&nbsp;a,&nbsp;<span style="color:blue;">Monoid</span>&nbsp;a)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Property</span> leftIdLaw&nbsp;x&nbsp;=&nbsp;x&nbsp;===&nbsp;mempty&nbsp;&lt;&gt;&nbsp;x <span style="color:#2b91af;">rightIdLaw</span>&nbsp;::&nbsp;(<span style="color:blue;">Eq</span>&nbsp;a,&nbsp;<span style="color:blue;">Show</span>&nbsp;a,&nbsp;<span style="color:blue;">Monoid</span>&nbsp;a)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Property</span> rightIdLaw&nbsp;x&nbsp;=&nbsp;x&nbsp;===&nbsp;x&nbsp;&lt;&gt;&nbsp;mempty </pre> </p> <p> Again, this is entirely generic. These properties can be used to test the identity laws for any monoid, including <code>Monap</code>. </p> <h3 id="0cc5968e519c48a0816574e1dc1667fc"> Properties <a href="#0cc5968e519c48a0816574e1dc1667fc" title="permalink">#</a> </h3> <p> You can run each of these properties multiple time, for various different functors and monoids. As <code>Applicative</code> instances, I've used <code>Maybe</code>, <code>[]</code>, <code>(,) Any</code>, and <code>Identity</code>. As <code>Monoid</code> instances, I've used <code>String</code>, <code>Sum Integer</code>, <code>Max Int16</code>, and <code>[Float]</code>. Notice that a list (<code>[]</code>) is both an applicative functor as well as a monoid. In this test set, I've used it in both roles. </p> <p> <pre>tests&nbsp;= &nbsp;&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;testGroup&nbsp;<span style="color:#a31515;">&quot;Properties&quot;</span>&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;testProperty&nbsp;<span style="color:#a31515;">&quot;Associativity&nbsp;law,&nbsp;Maybe&nbsp;String&quot;</span>&nbsp;(assocLaw&nbsp;@(Monap&nbsp;Maybe&nbsp;String)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;testProperty&nbsp;<span style="color:#a31515;">&quot;Left&nbsp;identity&nbsp;law,&nbsp;Maybe&nbsp;String&quot;</span>&nbsp;(leftIdLaw&nbsp;@(Monap&nbsp;Maybe&nbsp;String)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;testProperty&nbsp;<span style="color:#a31515;">&quot;Right&nbsp;identity&nbsp;law,&nbsp;Maybe&nbsp;String&quot;</span>&nbsp;(rightIdLaw&nbsp;@(Monap&nbsp;Maybe&nbsp;String)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;testProperty&nbsp;<span style="color:#a31515;">&quot;Associativity&nbsp;law,&nbsp;[Sum&nbsp;Integer]&quot;</span>&nbsp;(assocLaw&nbsp;@(Monap&nbsp;<span style="color:blue;">[]</span>&nbsp;(Sum&nbsp;Integer))), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;testProperty&nbsp;<span style="color:#a31515;">&quot;Left&nbsp;identity&nbsp;law,&nbsp;[Sum&nbsp;Integer]&quot;</span>&nbsp;(leftIdLaw&nbsp;@(Monap&nbsp;<span style="color:blue;">[]</span>&nbsp;(Sum&nbsp;Integer))), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;testProperty&nbsp;<span style="color:#a31515;">&quot;Right&nbsp;identity&nbsp;law,&nbsp;[Sum&nbsp;Integer]&quot;</span>&nbsp;(rightIdLaw&nbsp;@(Monap&nbsp;<span style="color:blue;">[]</span>&nbsp;(Sum&nbsp;Integer))), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;testProperty&nbsp;<span style="color:#a31515;">&quot;Associativity&nbsp;law,&nbsp;(Any,&nbsp;Max&nbsp;Int8)&quot;</span>&nbsp;(assocLaw&nbsp;@(Monap&nbsp;(<span style="color:#2b91af;">(,)</span>&nbsp;Any)&nbsp;(Max&nbsp;Int8))), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;testProperty&nbsp;<span style="color:#a31515;">&quot;Left&nbsp;identity&nbsp;law,&nbsp;(Any,&nbsp;Max&nbsp;Int8)&quot;</span>&nbsp;(leftIdLaw&nbsp;@(Monap&nbsp;(<span style="color:#2b91af;">(,)</span>&nbsp;Any)&nbsp;(Max&nbsp;Int8))), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;testProperty&nbsp;<span style="color:#a31515;">&quot;Right&nbsp;identity&nbsp;law,&nbsp;(Any,&nbsp;Max&nbsp;Int8)&quot;</span>&nbsp;(rightIdLaw&nbsp;@(Monap&nbsp;(<span style="color:#2b91af;">(,)</span>&nbsp;Any)&nbsp;(Max&nbsp;Int8))), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;testProperty&nbsp;<span style="color:#a31515;">&quot;Associativity&nbsp;law,&nbsp;Identity&nbsp;[Float]&quot;</span>&nbsp;(assocLaw&nbsp;@(Monap&nbsp;Identity&nbsp;[Float])), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;testProperty&nbsp;<span style="color:#a31515;">&quot;Left&nbsp;identity&nbsp;law,&nbsp;Identity&nbsp;[Float]&quot;</span>&nbsp;(leftIdLaw&nbsp;@(Monap&nbsp;Identity&nbsp;[Float])), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;testProperty&nbsp;<span style="color:#a31515;">&quot;Right&nbsp;identity&nbsp;law,&nbsp;Identity&nbsp;[Float]&quot;</span>&nbsp;(rightIdLaw&nbsp;@(Monap&nbsp;Identity&nbsp;[Float])) &nbsp;&nbsp;&nbsp;&nbsp;] &nbsp;&nbsp;] </pre> </p> <p> All of these properties pass. </p> <h3 id="af35f2986a734a16be80590c86d0432d"> Summary <a href="#af35f2986a734a16be80590c86d0432d" title="permalink">#</a> </h3> <p> It seems that any applicative functor that contains monoidal values itself forms a monoid. The <code>Monap</code> type presented in this article only exists to demonstrate this conjecture; it's not intended to be <em>used</em>. </p> <p> If it holds, I think it's an interesting result, because it further enables you to reason about the properties of complex systems, based on the properties of simpler systems. </p> <p> <strong>Next: </strong> <a href="/2018/12/24/bifunctors">Bifunctors</a>. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="9a3acf3cf4174e178dc9349e11fee488"> <div class="comment-author">Tyson Williams</div> <div class="comment-content"> <blockquote> It seems that any applicative functor that contains monoidal values itself forms a monoid. </blockquote> <p> Is it necessary for the functor to be applicative? Do know of a functor that contains monoidal values for which itself does <em>not</em> form a monoid? </p> </div> <div class="comment-date">2019-05-13 11:28 UTC</div> </div> <div class="comment" id="a164909adb884cd78b309a81029a2dd8"> <div class="comment-author"><a href="/">Mark Seemann</a></div> <div class="comment-content"> <p> Tyson, thank you for writing. Yes, it's necessary for the functor to be applicative, because you need the applicative combination operator <code>&lt;*&gt;</code> in order to implement the combination. In C#, you'd need an <code>Apply</code> method <a href="/2018/10/01/applicative-functors/#cef395ee19644f30bfd1ad7a84b6f912">as shown here</a>. </p> <p> Technically, the monoidal <code>&lt;&gt;</code> operator for <code>Monap</code> is, as you can see, implemented with a call to <code>liftA2</code>. In Haskell, you can implement an instance of <code>Applicative</code> by implementing either <code>liftA2</code> or <code>&lt;*&gt;</code>, as well as <code>pure</code>. You usually see <code>Applicative</code> described by <code>&lt;*&gt;</code>, which is what I've done in <a href="/2018/10/01/applicative-functors">my article series on applicative functors</a>. If you do that, you can define <code>liftA2</code> by a combination of <code>&lt;*&gt;</code> and <code>fmap</code> (the <code>Select</code> method that defines functors). </p> <p> If you want to put this in C# terms, you need both <code>Select</code> and <code>Apply</code> in order to be able to lift a monoid into a functor. </p> <p> Is there a functor that contains monoidal values that itself doesn't form a monoid? </p> <p> Yes, indeed. In order to answer that question, we 'just' need to identify a functor that's <em>not</em> an applicative functor. Tuples are good examples. </p> <p> A <a href="https://blog.ploeh.dk/2018/12/31/tuple-bifunctor/#d918d0271c33406ba3047ef162212100">tuple forms a functor</a>, but in general nothing more than that. Consider a tuple where the first element is a <code>Guid</code>. It's a functor, but can you implement the following function? </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">Guid</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;Apply&lt;<span style="color:#2b91af;">TResult</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">Guid</span>,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;selector, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">Guid</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;source) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">NotImplementedException</span>(<span style="color:#a31515;">&quot;What&nbsp;would&nbsp;you&nbsp;write&nbsp;here?&quot;</span>); }</pre> </p> <p> You can pull the <code>T</code> value out of <code>source</code> and project it to a <code>TResult</code> value with <code>selector</code>, but you'll need to put it back in a <code>Tuple&lt;Guid, TResult&gt;</code>. Which <code>Guid</code> value are you going to use for that tuple? </p> <p> There's no clear answer to that question. </p> <p> More specifically, consider <code>Tuple&lt;Guid, int&gt;</code>. This is a functor that contains monoidal values. Let's say that we want to use the addition monoid over integers. How would you implement the following method? </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">Guid</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;Add(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">Guid</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">Guid</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">NotImplementedException</span>(<span style="color:#a31515;">&quot;What&nbsp;would&nbsp;you&nbsp;write&nbsp;here?&quot;</span>); }</pre> </p> <p> Again, you run into the issue that while you can pull the integers out of the tuples and add them together, there's no clear way to figure out which <code>Guid</code> value to put into the tuple that contains the sum. </p> <p> The issue particularly with tuples is that there's no general way to combine the leftmost values of the tuples. If there is - that is, if leftmost values form a monoid - then the tuple is also an applicative functor. For example, <code>Tuple&lt;string, int&gt;</code> is applicative and forms a monoid over addition: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;Apply&lt;<span style="color:#2b91af;">TResult</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;selector, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;source) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">Tuple</span>.Create( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;selector.Item1&nbsp;+&nbsp;source.Item1, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;selector.Item2(source.Item2)); } <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;Add(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">Tuple</span>.Create(x.Item1&nbsp;+&nbsp;y.Item1,&nbsp;x.Item2&nbsp;+&nbsp;y.Item2); }</pre> </p> <p> You can also implement <code>Add</code> with <code>Apply</code>, but you're going to need two <code>Apply</code> overloads to make it work. </p> <p> Incidentally, unbeknownst to me, the <code>Ap</code> wrapper was added to Haskell's <code>Data.Monoid</code> module 12 days before I wrote this article. In all but name, it's equivalent to the <code>Monap</code> wrapper presented here. </p> </div> <div class="comment-date">2019-05-14 20:44 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2019/04/22/applicative-monoids Lazy monoids https://blog.ploeh.dk/2019/04/15/lazy-monoids/ Mon, 15 Apr 2019 13:54:00 UTC <div id="post"> <p> <em>Lazy monoids are monoids. An article for object-oriented programmers.</em> </p> <p> This article is part of a <a href="/2017/10/06/monoids">series about monoids</a>. In short, a <em>monoid</em> is an associative binary operation with a neutral element (also known as <em>identity</em>). Previous articles have shown how more complex monoids arise from simpler monoids, such as <a href="/2017/10/30/tuple-monoids">tuple monoids</a>, <a href="/2017/11/06/function-monoids">function monoids</a>, and <a href="/2018/04/03/maybe-monoids">Maybe monoids</a>. This article shows another such result: how lazy computations of monoids itself form monoids. </p> <p> You'll see how simple this is through a series of examples. Specifically, you'll revisit several of the examples you've already seen in this article series. </p> <h3 id="a715cff45376401db9863a095a5e156d"> Lazy addition <a href="#a715cff45376401db9863a095a5e156d" title="permalink">#</a> </h3> <p> Perhaps the most intuitive monoid is <em>addition</em>. Lazy addition forms a monoid as well. In C#, you can implement this with a simple extension method: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;Add(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;(()&nbsp;=&gt;&nbsp;x.Value&nbsp;+&nbsp;y.Value); }</pre> </p> <p> This <code>Add</code> method simply adds two lazy integers together in a lazy computation. You use it like any other extension method: </p> <p> <pre><span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;x&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;y&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;sum&nbsp;=&nbsp;x.Add(y);</pre> </p> <p> I'll spare you the tedious listing of <a href="https://fscheck.github.io/FsCheck">FsCheck</a>-based properties that demonstrate that the monoid laws hold. We'll look at an example of such a set of properties later in this article, for one of the other monoids. </p> <h3 id="eda5d39029904d70995ebee84570cf60"> Lazy multiplication <a href="#eda5d39029904d70995ebee84570cf60" title="permalink">#</a> </h3> <p> Not surprisingly, I hope, you can implement multiplication over lazy numbers in the same way: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;Multiply(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;(()&nbsp;=&gt;&nbsp;x.Value&nbsp;*&nbsp;y.Value); }</pre> </p> <p> Usage is similar to lazy addition: </p> <p> <pre><span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;x&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;y&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;product&nbsp;=&nbsp;x.Multiply(y);</pre> </p> <p> As is the case with lazy addition, this <code>Multiply</code> method currently only works with lazy <code>int</code> values. If you also want it to work with <code>long</code>, <code>short</code>, or other types of numbers, you'll have to add method overloads. </p> <h3 id="93b85bb3c55045dabdb16fd11167dad7"> Lazy Boolean monoids <a href="#93b85bb3c55045dabdb16fd11167dad7" title="permalink">#</a> </h3> <p> There are four monoids over Boolean values, although I've customarily only shown two of them: <em>and</em> and <em>or</em>. These also, trivially, work with lazy Boolean values: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;And(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;(()&nbsp;=&gt;&nbsp;x.Value&nbsp;&amp;&amp;&nbsp;y.Value); } <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;Or(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;(()&nbsp;=&gt;&nbsp;x.Value&nbsp;||&nbsp;y.Value); }</pre> </p> <p> Given the previous examples, you'll hardly be surprised to see how you can use one of these extension methods: </p> <p> <pre><span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;x&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;y&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;b&nbsp;=&nbsp;x.And(y);</pre> </p> <p> Have you noticed a pattern in how the lazy binary operations <code>Add</code>, <code>Multiply</code>, <code>And</code>, and <code>Or</code> are implemented? Could this be generalised? </p> <h3 id="12b7d0077481413cab6acf8f6bf696cf"> Lazy angular addition <a href="#12b7d0077481413cab6acf8f6bf696cf" title="permalink">#</a> </h3> <p> In a previous article you saw how <a href="/2018/07/16/angular-addition-monoid">angular addition forms a monoid</a>. Lazy angular addition forms a monoid as well, which you can implement with another extension method: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Angle</span>&gt;&nbsp;Add(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Angle</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Angle</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Angle</span>&gt;(()&nbsp;=&gt;&nbsp;x.Value.Add(y.Value)); }</pre> </p> <p> Until now, you may have noticed that all the extension methods seemed to follow a common pattern that looks like this: </p> <p> <pre><span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Foo</span>&gt;(()&nbsp;=&gt;&nbsp;x.Value&nbsp;&diamond;&nbsp;y.Value);</pre> </p> <p> I've here used the diamond operator <code>&diamond;</code> as a place-holder for any sort of binary operation. My choice of that particular character is strongly influenced by <a href="https://www.haskell.org">Haskell</a>, where <a href="/2017/11/27/semigroups">semigroups</a> and monoids polymorphically are modelled with (among other options) the <code>&lt;&gt;</code> operator. </p> <p> The lazy angular addition implementation looks a bit different, though. This is because the original example uses an instance method to model the binary operation, instead of an infix operator such as <code>+</code>, <code>&&</code>, and so on. Given that the implementation of a lazy binary operation can also look like this, can you still imagine a generalisation? </p> <h3 id="669710b096144c6d8aaaca4426f8f795"> Lazy string concatenation <a href="#669710b096144c6d8aaaca4426f8f795" title="permalink">#</a> </h3> <p> If we follow the rough ordering of examples introduced in this article series about monoids, we've now reached <a href="/2017/10/10/strings-lists-and-sequences-as-a-monoid">concatenation as a monoid</a>. While various lists, arrays, and other sorts of collections also form a monoid over concatenation, in .NET, <code>IEnumerable&lt;T&gt;</code> already enables lazy evaluation, so I think it's more interesting to consider lazy string concatenation. </p> <p> The implementation, however, holds few surprises: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;Concat(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">string</span>&gt;(()&nbsp;=&gt;&nbsp;x.Value&nbsp;+&nbsp;y.Value); }</pre> </p> <p> The overall result, so far, seems encouraging. All the basic monoids we've covered are also monoids when lazily computed. </p> <h3 id="29df873ebae145e2b903f6562825b69e"> Lazy money addition <a href="#29df873ebae145e2b903f6562825b69e" title="permalink">#</a> </h3> <p> The portfolio example from Kent Beck's book <a href="http://bit.ly/tddbe">Test-Driven Development By Example</a> also <a href="/2017/10/16/money-monoid">forms a monoid</a>. You can, again, implement an extension method that enables you to add lazy expressions together: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;Plus( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;source, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;addend) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;(()&nbsp;=&gt;&nbsp;source.Value.Plus(addend.Value)); }</pre> </p> <p> So far, you've seen several examples of implementations, but are they really monoids? All are clearly binary operations, but are they associative? Do identities exist? In other words, do the lazy binary operations obey the monoid laws? </p> <p> As usual, I'm not going to prove that they do, but I do want to share a set of FsCheck properties that demonstrate that the monoid laws hold. As an example, I'll share the properties for this lazy <code>Plus</code> method, but you can write similar properties for all of the above methods as well. </p> <p> You can verify the associativity law like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;LazyPlusIsAssociative( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;x, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;y, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;z) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;x.Plus(y).Plus(z), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;x.Plus(y.Plus(z)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Compare</span>.UsingBank); }</pre> </p> <p> Here, <code>Compare.UsingBank</code> is just a <a href="http://xunitpatterns.com/Test%20Utility%20Method.html">test utility API</a> to make the code more readable: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Compare</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">ExpressionEqualityComparer</span>&nbsp;UsingBank&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ExpressionEqualityComparer</span>(); }</pre> </p> <p> This takes advantage of the overloads for <a href="https://xunit.github.io">xUnit.net</a>'s <code>Assert</code> methods that take custom equality comparers as an extra, optional argument. <code>ExpressionEqualityComparer</code> is implemented in the test code base: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">ExpressionEqualityComparer</span>&nbsp;: &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IEqualityComparer</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;,&nbsp;<span style="color:#2b91af;">IEqualityComparer</span>&lt;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">Bank</span>&nbsp;bank; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;ExpressionEqualityComparer() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;bank&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Bank</span>(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;bank.AddRate(<span style="color:#a31515;">&quot;CHF&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;USD&quot;</span>,&nbsp;2); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;Equals(<span style="color:#2b91af;">IExpression</span>&nbsp;x,&nbsp;<span style="color:#2b91af;">IExpression</span>&nbsp;y) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;xm&nbsp;=&nbsp;bank.Reduce(x,&nbsp;<span style="color:#a31515;">&quot;USD&quot;</span>); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;ym&nbsp;=&nbsp;bank.Reduce(y,&nbsp;<span style="color:#a31515;">&quot;USD&quot;</span>); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">object</span>.Equals(xm,&nbsp;ym); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">int</span>&nbsp;GetHashCode(<span style="color:#2b91af;">IExpression</span>&nbsp;obj) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;bank.Reduce(obj,&nbsp;<span style="color:#a31515;">&quot;USD&quot;</span>).GetHashCode(); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;Equals(<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;y) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;Equals(x.Value,&nbsp;y.Value); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">int</span>&nbsp;GetHashCode(<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;obj) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;GetHashCode(obj.Value); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> If you think that the exchange rate between Dollars and Swiss Francs looks ridiculous, it's because I'm using the rate that Kent Beck used in his book, which is from 2002 (but otherwise timeless). </p> <p> The above property passes for hundreds of randomly generated input values, as is the case for this property, which verifies the left and right identity: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;LazyPlusHasIdentity(<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;x) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(x,&nbsp;x.Plus(<span style="color:#2b91af;">Plus</span>.Identity.ToLazy()),&nbsp;<span style="color:#2b91af;">Compare</span>.UsingBank); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(x,&nbsp;<span style="color:#2b91af;">Plus</span>.Identity.ToLazy().Plus(x),&nbsp;<span style="color:#2b91af;">Compare</span>.UsingBank); }</pre> </p> <p> These properties are just examples, not proofs. Still, they give confidence that lazy computations of monoids are themselves monoids. </p> <h3 id="6b5aa8f3a0b34d4c9d145eac3e59fe9b"> Lazy Roster combinations <a href="#6b5aa8f3a0b34d4c9d145eac3e59fe9b" title="permalink">#</a> </h3> <p> The last example you'll get in this article is the <code>Roster</code> example from the article on <a href="/2017/10/30/tuple-monoids">tuple monoids</a>. Here's yet another extension method that enables you to combine to lazy rosters: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Roster</span>&gt;&nbsp;Combine(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Roster</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Roster</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Roster</span>&gt;(()&nbsp;=&gt;&nbsp;x.Value.Combine(y.Value)); }</pre> </p> <p> At this point it should be clear that there's essentially two variations in how the above extension methods are implemented. One variation is when the binary operation is implemented with an infix operator (like <code>+</code>, <code>||</code>, and so on), and another variation is when it's modelled as an instance method. How do these implementations generalise? </p> <p> I'm sure you could come up with an ad-hoc higher-order function, abstract base class, or interface to model such a generalisation, but I'm not motivated by <a href="/2018/09/17/typing-is-not-a-programming-bottleneck">saving keystrokes</a>. What I'm trying to uncover with this <a href="/2017/10/04/from-design-patterns-to-category-theory">overall article series</a> is how universal abstractions apply to programming. </p> <p> Which universal abstraction is in play here? </p> <h3 id="6d247327cf214fa698dc9ec29693bd6f"> Lazy monoids as applicative operations <a href="#6d247327cf214fa698dc9ec29693bd6f" title="permalink">#</a> </h3> <p> <a href="/2018/12/17/the-lazy-applicative-functor">Lazy&lt;T&gt; forms an applicative functor</a>. Using appropriate <code>Apply</code> overloads, you can rewrite all the above implementations in applicative style. Here's lazy addition: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;Add(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;f&nbsp;=&nbsp;(i,&nbsp;j)&nbsp;=&gt;&nbsp;i&nbsp;+&nbsp;j; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;f.Apply(x).Apply(y); }</pre> </p> <p> This first declares a <code>Func</code> value <code>f</code> that invokes the non-lazy binary operation, in this case <code>+</code>. Next, you can leverage the applicative nature of <code>Lazy&lt;T&gt;</code> to apply <code>f</code> to the two lazy values <code>x</code> and <code>y</code>. </p> <p> Multiplication, as well as the Boolean operations, follow the exact same template: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;Multiply(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;f&nbsp;=&nbsp;(i,&nbsp;j)&nbsp;=&gt;&nbsp;i&nbsp;*&nbsp;j; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;f.Apply(x).Apply(y); } <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;And(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">bool</span>,&nbsp;<span style="color:blue;">bool</span>,&nbsp;<span style="color:blue;">bool</span>&gt;&nbsp;f&nbsp;=&nbsp;(b1,&nbsp;b2)&nbsp;=&gt;&nbsp;b1&nbsp;&amp;&amp;&nbsp;b2; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;f.Apply(x).Apply(y); } <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;Or(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">bool</span>,&nbsp;<span style="color:blue;">bool</span>,&nbsp;<span style="color:blue;">bool</span>&gt;&nbsp;f&nbsp;=&nbsp;(b1,&nbsp;b2)&nbsp;=&gt;&nbsp;b1&nbsp;||&nbsp;b2; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;f.Apply(x).Apply(y); }</pre> </p> <p> Notice that in all four implementations, the second line of code is verbatim the same: <code>return f.Apply(x).Apply(y);</code> </p> <p> Does this generalisation also hold when the underlying, non-lazy binary operation is modelled as an instance method, as is the case of e.g. angular addition? Yes, indeed: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Angle</span>&gt;&nbsp;Add(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Angle</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Angle</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Angle</span>,&nbsp;<span style="color:#2b91af;">Angle</span>,&nbsp;<span style="color:#2b91af;">Angle</span>&gt;&nbsp;f&nbsp;=&nbsp;(i,&nbsp;j)&nbsp;=&gt;&nbsp;i.Add(j); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;f.Apply(x).Apply(y); }</pre> </p> <p> You can implement the <code>Combine</code> method for lazy <code>Roster</code> objects in the same way, as well as <code>Plus</code> for lazy monetary expressions. The latter is worth revisiting. </p> <h3 id="445af7622459483ab64f4ff31ceb1c2e"> Using the Lazy functor over portfolio expressions <a href="#445af7622459483ab64f4ff31ceb1c2e" title="permalink">#</a> </h3> <p> The lazy <code>Plus</code> implementation looks like all of the above <code>Apply</code>-based implementations: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;Plus( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;source,&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;addend) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">IExpression</span>,&nbsp;<span style="color:#2b91af;">IExpression</span>,&nbsp;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;f&nbsp;=&nbsp;(x,&nbsp;y)&nbsp;=&gt;&nbsp;x.Plus(y); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;f.Apply(source).Apply(addend); }</pre> </p> <p> In my article, however, you saw how, when <code>Plus</code> is a monoid, you can implement <code>Times</code> as an extension method. Can you implement a lazy version of <code>Times</code> as well? Must it be another extension method? </p> <p> Yes, but instead of an ad-hoc implementation, you can take advantage of the functor nature of Lazy: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;Times(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;exp,&nbsp;<span style="color:blue;">int</span>&nbsp;multiplier) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;exp.Select(x&nbsp;=&gt;&nbsp;x.Times(multiplier)); }</pre> </p> <p> Notice that instead of explicitly reaching into the lazy <code>Value</code>, you can simply call <code>Select</code> on <code>exp</code>. This lazily projects the <code>Times</code> operation, while preserving the invariants of <code>Lazy&lt;T&gt;</code> (i.e. that the computation is deferred until you ultimately access the <code>Value</code> property). </p> <p> You can implement a lazy version of <code>Reduce</code> in the same way: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Money</span>&gt;&nbsp;Reduce(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;exp,&nbsp;<span style="color:#2b91af;">Bank</span>&nbsp;bank,&nbsp;<span style="color:blue;">string</span>&nbsp;to) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;exp.Select(x&nbsp;=&gt;&nbsp;x.Reduce(bank,&nbsp;to)); }</pre> </p> <p> The question is, however, is it even worthwhile? Do you need to create all these overloads, or could you just leverage <code>Select</code> when you have a lazy value? </p> <p> For example, if the above <code>Reduce</code> overload didn't exist, you'd still be able to work with the portfolio API like this: </p> <p> <pre><span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;portfolio&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Money</span>&gt;&nbsp;result&nbsp;=&nbsp;portfolio.Select(x&nbsp;=&gt;&nbsp;x.Reduce(bank,&nbsp;<span style="color:#a31515;">&quot;USD&quot;</span>));</pre> </p> <p> If you only occasionally use <code>Reduce</code>, then perhaps this is good enough. If you frequently call <code>Reduce</code>, however, it might be worth to add the above overload, in which case you could then instead write: </p> <p> <pre><span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IExpression</span>&gt;&nbsp;portfolio&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Money</span>&gt;&nbsp;result&nbsp;=&nbsp;portfolio.Reduce(bank,&nbsp;<span style="color:#a31515;">&quot;USD&quot;</span>);</pre> </p> <p> In both cases, however, I think that you'd be putting the concept of an applicative functor to good use. </p> <h3 id="a5942465683c459a92457ea13e3bd21d"> Towards generalisation <a href="#a5942465683c459a92457ea13e3bd21d" title="permalink">#</a> </h3> <p> Is the applicative style better than the initial ad-hoc implementations? That depends on how you evaluate 'better'. If you count lines of code, then the applicative style is twice as verbose as the ad-hoc implementations. In other words, this: </p> <p> <pre><span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;(()&nbsp;=&gt;&nbsp;x.Value&nbsp;+&nbsp;y.Value);</pre> </p> <p> seems simpler than this: </p> <p> <pre><span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;f&nbsp;=&nbsp;(i,&nbsp;j)&nbsp;=&gt;&nbsp;i&nbsp;+&nbsp;j; <span style="color:blue;">return</span>&nbsp;f.Apply(x).Apply(y);</pre> </p> <p> This is, however, mostly because C# is too weak to express such abstractions in an elegant way. In <a href="https://fsharp.org">F#</a>, using the custom <code>&lt;*&gt;</code> operator from <a href="/2018/12/17/the-lazy-applicative-functor">the article on the Lazy applicative functor</a>, you could express the lazy addition as simply as: </p> <p> <pre><span style="color:blue;">lazy</span>&nbsp;(+)&nbsp;&lt;*&gt;&nbsp;x&nbsp;&lt;*&gt;&nbsp;y</pre> </p> <p> In <a href="https://www.haskell.org">Haskell</a> (if we, once more, pretend that <code>Identity</code> is equivalent to <code>Lazy</code>), you can simplify even further to: </p> <p> <pre>(+) &lt;$&gt; x &lt;*&gt; y</pre> </p> <p> Or rather, if you want it in <a href="https://en.wikipedia.org/wiki/Tacit_programming">point-free style</a>, <code>liftA2 (+)</code>. </p> <h3 id="f418f44f772b44c287365c7054d51aa1"> Summary <a href="#f418f44f772b44c287365c7054d51aa1" title="permalink">#</a> </h3> <p> The point of this article series isn't to save keystrokes, but to identify universal laws of computing, even as they relate to object-oriented programming. The pattern seems clear enough that I dare propose the following: </p> <p> <em>All monoids remain monoids under lazy computation.</em> </p> <p> In a future article I'll offer further support for that proposition. </p> <p> <strong>Next:</strong> <a href="/2017/11/20/monoids-accumulate">Monoids accumulate</a>. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2019/04/15/lazy-monoids A pure Test Spy https://blog.ploeh.dk/2019/04/08/a-pure-test-spy/ Mon, 08 Apr 2019 06:02:00 UTC <div id="post"> <p> <em>Ad-hoc Test Spies can be implemented in Haskell using the Writer monad.</em> </p> <p> In a previous article on <a href="/2019/03/11/an-example-of-state-based-testing-in-haskell">state-based testing in Haskell</a>, I made the following throw-away statement: <blockquote> "you <em>could</em> write an ad-hoc Mock using, for example, the Writer monad" </blockquote> In that article, I didn't pursue that thought, since the theme was another. Instead, I'll expand on it here. </p> <h3 id="552a47e82a99466ebb8fe9d840b80a2f"> Test Double continuum <a href="#552a47e82a99466ebb8fe9d840b80a2f" title="permalink">#</a> </h3> <p> More than a decade ago, I wrote an MSDN Magazine article called <em>Exploring The Continuum Of Test Doubles</em>. It was in the September 2007 issue, and since then, the Magazine restructured so that the article is no longer available online. You can still <a href="https://msdn.microsoft.com/en-us/magazine/msdn-magazine-issues.aspx">download the entire issue as a single file</a> and read the article offline, should you want to. </p> <p> In the article, I made the argument that the classification of <a href="http://xunitpatterns.com/Test%20Double.html">Test Doubles</a> presented in the excellent <a href="http://bit.ly/xunitpatterns">xUnit Test Patterns</a> should be thought of more as a continuum with vague and fuzzy transitions, rather than discrete categories. </p> <p> <img src="/content/binary/msdn-test-double-continuum.png" alt="Spectrum of Test Doubles."> </p> <p> This figure appeared in the original article. Given that the entire MSDN Magazine issue is available for free, and that I'm the original author of the article, I consider it fair use to repeat it here. </p> <p> The point is that it's not always clear whether a Test Double is, say, a Mock, or a Spy. What I'll show you in this article is closer to a Test Spy than to a Mock, but since the distinction is blurred anyway, I think that I can get away with it. </p> <h3 id="200ba4d9157442fe9caef2429371f7c6"> Test Spy <a href="#200ba4d9157442fe9caef2429371f7c6" title="permalink">#</a> </h3> <p> <em>xUnit Test Patterns</em> defines a Test Spy as a Test Double that captures "the indirect output calls made to another component by the SUT [System Under Test] for later verification by the test." When, as shown in <a href="/2019/02/25/an-example-of-interaction-based-testing-in-c">a previous article</a>, you use <code>Mock&lt;T&gt;.Verify</code> to assert than an interaction took place, you're using the Test Double more as a Spy than a Mock: </p> <p> <pre>repoTD.Verify(r&nbsp;=&gt;&nbsp;r.Update(user));</pre> </p> <p> Strictly speaking, a Mock is a Test Double that <em>immediately</em> fails the test if any unexpected interaction takes place. People often call those <em>Strict Mocks</em>, but according to the book, that's a Mock. If the Test Double only records what happens, so that you can later query it to verify whether some interaction took place, it's closer to being a Test Spy. </p> <p> Whether you call it a Mock or a Spy, you can implement verification similar to the above <code>Verify</code> method in functional programming using the Writer monad. </p> <h3 id="cf14cbf8e65a4dd6a47f879c1b850de5"> Writer-based Spy <a href="#cf14cbf8e65a4dd6a47f879c1b850de5" title="permalink">#</a> </h3> <p> I'll show you a single example in <a href="https://www.haskell.org">Haskell</a>. In <a href="http://blog.ploeh.dk/2018/07/30/flattening-arrow-code-using-a-stack-of-monads">a previous article</a>, you saw a simplified function to implement a restaurant reservation feature, repeated here for your convenience: </p> <p> <pre><span style="color:#2b91af;">tryAccept</span>&nbsp;::&nbsp;<span style="color:#2b91af;">Int</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Reservation</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">MaybeT</span>&nbsp;<span style="color:blue;">ReservationsProgram</span>&nbsp;<span style="color:#2b91af;">Int</span> tryAccept&nbsp;capacity&nbsp;reservation&nbsp;=&nbsp;<span style="color:blue;">do</span> &nbsp;&nbsp;guard&nbsp;=&lt;&lt;&nbsp;isReservationInFuture&nbsp;reservation &nbsp;&nbsp;reservations&nbsp;&lt;-&nbsp;readReservations&nbsp;$&nbsp;reservationDate&nbsp;reservation &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;reservedSeats&nbsp;=&nbsp;<span style="color:blue;">sum</span>&nbsp;$&nbsp;reservationQuantity&nbsp;&lt;$&gt;&nbsp;reservations &nbsp;&nbsp;guard&nbsp;$&nbsp;reservedSeats&nbsp;+&nbsp;reservationQuantity&nbsp;reservation&nbsp;&lt;=&nbsp;capacity &nbsp;&nbsp;create&nbsp;$&nbsp;reservation&nbsp;{&nbsp;reservationIsAccepted&nbsp;=&nbsp;True&nbsp;} </pre> </p> <p> This function runs in the <code>MaybeT</code> monad, so the two <code>guard</code> functions could easily prevent if from running 'to completion'. In the happy path, though, execution should reach 'the end' of the function and call the <code>create</code> function. </p> <p> In order to test this happy path, you'll need to not only run a test-specific interpreter over the <code>ReservationsProgram</code> free monad, you should also verify that <code>reservationIsAccepted</code> is <code>True</code>. </p> <p> You can do this using the <code>Writer</code> monad to implement a Test Spy: </p> <p> <pre>testProperty&nbsp;<span style="color:#a31515;">&quot;tryAccept,&nbsp;happy&nbsp;path&quot;</span>&nbsp;$&nbsp;\ &nbsp;&nbsp;(NonNegative&nbsp;i) &nbsp;&nbsp;(<span style="color:blue;">fmap</span>&nbsp;getReservation&nbsp;-&gt;&nbsp;reservations) &nbsp;&nbsp;(ArbReservation&nbsp;reservation) &nbsp;&nbsp;expected &nbsp;&nbsp;-&gt; &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;spy&nbsp;(IsReservationInFuture&nbsp;_&nbsp;next)&nbsp;=&nbsp;<span style="color:blue;">return</span>&nbsp;$&nbsp;next&nbsp;True &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;spy&nbsp;(ReadReservations&nbsp;_&nbsp;next)&nbsp;=&nbsp;<span style="color:blue;">return</span>&nbsp;$&nbsp;next&nbsp;reservations &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;spy&nbsp;(Create&nbsp;r&nbsp;next)&nbsp;=&nbsp;tell&nbsp;[r]&nbsp;&gt;&gt;&nbsp;<span style="color:blue;">return</span>&nbsp;(next&nbsp;expected) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;reservedSeats&nbsp;=&nbsp;<span style="color:blue;">sum</span>&nbsp;$&nbsp;reservationQuantity&nbsp;&lt;$&gt;&nbsp;reservations &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;capacity&nbsp;=&nbsp;reservedSeats&nbsp;+&nbsp;reservationQuantity&nbsp;reservation&nbsp;+&nbsp;i &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(actual,&nbsp;observedReservations)&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;runWriter&nbsp;$&nbsp;foldFreeT&nbsp;spy&nbsp;$&nbsp;runMaybeT&nbsp;$&nbsp;tryAccept&nbsp;capacity&nbsp;reservation &nbsp;&nbsp;<span style="color:blue;">in</span>&nbsp;&nbsp;Just&nbsp;expected&nbsp;==&nbsp;actual&nbsp;&amp;&amp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[True]&nbsp;==&nbsp;(reservationIsAccepted&nbsp;&lt;$&gt;&nbsp;observedReservations)</pre> </p> <p> This test is an <a href="http://blog.ploeh.dk/2018/05/07/inlined-hunit-test-lists">inlined</a> QuickCheck-based property. The entire <a href="https://github.com/ploeh/dependency-injection-revisited">source code is available on GitHub</a>. </p> <p> Notice the <code>spy</code> function. As the name implies, it's the Test Spy for the test. Its full type is: </p> <p> <pre>spy&nbsp;::&nbsp;Monad&nbsp;m&nbsp;=&gt;&nbsp;ReservationsInstruction&nbsp;a&nbsp;-&gt;&nbsp;WriterT&nbsp;[Reservation]&nbsp;m&nbsp;a</pre> </p> <p> This is a function that, for a given <code>ReservationsInstruction</code> value returns a <code>WriterT</code> value where the type of data being written is <code>[Reservation]</code>. The function only writes to the writer context in one of the three cases: the <code>Create</code> case. The <code>Create</code> case carries with it a <code>Reservation</code> value here named <code>r</code>. Before returning the <code>next</code> step in interpreting the free monad, the <code>spy</code> function calls <code>tell</code>, thereby writing a singleton list of <code>[r]</code> to the writer context. </p> <p> In the Act phase of the test, it calls the <code>tryAccept</code> function and proceeds to interpret the result, which is a <code>MaybeT ReservationsProgram Int</code> value. Calling <code>runMaybeT</code> produces a <code>ReservationsProgram (Maybe Int)</code>, which you can then interpret with <code>foldFreeT spy</code>. This returns a <code>Writer [Reservation] (Maybe Int)</code>, which you can finally run with <code>runWriter</code> to get a <code>(Maybe Int, [Reservation])</code> tuple. Thus, <code>actual</code> is a <code>Maybe Int</code> value, and <code>observedReservations</code> is a <code>[Reservation]</code> value - the reservation that was written by <code>spy</code> using <code>tell</code>. </p> <p> The Assert phase of the test is a Boolean expression that checks that <code>actual</code> is as expected, and that <code>reservationIsAccepted</code> of the observed reservation is <code>True</code>. </p> <p> It takes a little while to make the pieces of the puzzle fit, but it's basically just standard Haskell library functions clicked together. </p> <h3 id="fd3478dba1a241a7bb95d9a97140ebac"> Summary <a href="#fd3478dba1a241a7bb95d9a97140ebac" title="permalink">#</a> </h3> <p> People sometimes ask me: <em>How do Mocks and Stubs work in functional programming?</em> </p> <p> In general, my answer is that you don't need Mocks and Stubs because when functions are <a href="https://en.wikipedia.org/wiki/Pure_function">pure</a>, you don't need to to test interactions. Sooner or later, though, you may run into higher-level interactions, even if they're <a href="http://blog.ploeh.dk/2017/07/10/pure-interactions">pure interactions</a>, and you'll likely want to unit test those. </p> <p> In a previous article you saw how to apply <a href="/2019/03/11/an-example-of-state-based-testing-in-haskell">state-based testing in Haskell, using the State monad</a>. In this article you've seen how you can create ad-hoc Mocks or Spies with the Writer monad. No auto-magical test-specific 'isolation frameworks' are required. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2019/04/08/a-pure-test-spy An example of state-based testing in C# https://blog.ploeh.dk/2019/04/01/an-example-of-state-based-testing-in-c/ Mon, 01 Apr 2019 05:50:00 UTC <div id="post"> <p> <em>An example of avoiding Mocks and Stubs in C# unit testing.</em> </p> <p> This article is an instalment in an article series about how to move <a href="/2019/02/18/from-interaction-based-to-state-based-testing">from interaction-based testing to state-based testing</a>. In the previous article, you saw <a href="/2019/03/25/an-example-of-state-based-testing-in-f">an example of a pragmatic state-based test in F#</a>. You can now take your new-found knowledge and apply it to the <a href="/2019/02/25/an-example-of-interaction-based-testing-in-c">original C# example</a>. </p> <p> In the spirit of <a href="http://bit.ly/xunitpatterns">xUnit Test Patterns</a>, in this article you'll see how to refactor the tests while keeping the implementation code constant. </p> <p> The code shown in this article is <a href="https://github.com/ploeh/UserManagement">available on GitHub</a>. </p> <h3 id="da7f393fdef24bae9e72c4bcad7e8373"> Connect two users <a href="#da7f393fdef24bae9e72c4bcad7e8373" title="permalink">#</a> </h3> <p> The <a href="/2019/02/25/an-example-of-interaction-based-testing-in-c">previous article</a> provides more details on the System Under Test (SUT), but here it is, repeated, for your convenience: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">ConnectionsController</span>&nbsp;:&nbsp;<span style="color:#2b91af;">ApiController</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;ConnectionsController( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IUserReader</span>&nbsp;userReader, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IUserRepository</span>&nbsp;userRepository) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;UserReader&nbsp;=&nbsp;userReader; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;UserRepository&nbsp;=&nbsp;userRepository; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IUserReader</span>&nbsp;UserReader&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IUserRepository</span>&nbsp;UserRepository&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IHttpActionResult</span>&nbsp;Post(<span style="color:blue;">string</span>&nbsp;userId,&nbsp;<span style="color:blue;">string</span>&nbsp;otherUserId) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;userRes&nbsp;=&nbsp;UserReader.Lookup(userId).SelectError( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;error&nbsp;=&gt;&nbsp;error.Accept(<span style="color:#2b91af;">UserLookupError</span>.Switch( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;onInvalidId:&nbsp;<span style="color:#a31515;">&quot;Invalid&nbsp;user&nbsp;ID.&quot;</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;onNotFound:&nbsp;&nbsp;<span style="color:#a31515;">&quot;User&nbsp;not&nbsp;found.&quot;</span>))); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;otherUserRes&nbsp;=&nbsp;UserReader.Lookup(otherUserId).SelectError( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;error&nbsp;=&gt;&nbsp;error.Accept(<span style="color:#2b91af;">UserLookupError</span>.Switch( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;onInvalidId:&nbsp;<span style="color:#a31515;">&quot;Invalid&nbsp;ID&nbsp;for&nbsp;other&nbsp;user.&quot;</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;onNotFound:&nbsp;&nbsp;<span style="color:#a31515;">&quot;Other&nbsp;user&nbsp;not&nbsp;found.&quot;</span>))); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;connect&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;user&nbsp;<span style="color:blue;">in</span>&nbsp;userRes &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;otherUser&nbsp;<span style="color:blue;">in</span>&nbsp;otherUserRes &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;Connect(user,&nbsp;otherUser); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;connect.SelectBoth(Ok,&nbsp;BadRequest).Bifold(); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:#2b91af;">User</span>&nbsp;Connect(<span style="color:#2b91af;">User</span>&nbsp;user,&nbsp;<span style="color:#2b91af;">User</span>&nbsp;otherUser) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user.Connect(otherUser); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;UserRepository.Update(user); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;otherUser; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> This implementation code is a simplification of the code example that serves as an example running through my two <a href="https://cleancoders.com">Clean Coders</a> videos, <a href="https://cleancoders.com/episode/humane-code-real-episode-4/show">Church Visitor</a> and <a href="https://cleancoders.com/episode/humane-code-real-episode-5/show">Preserved in translation</a>. </p> <h3 id="4e6812ee83ad4cda9b8deedef99ab4e1"> A Fake database <a href="#4e6812ee83ad4cda9b8deedef99ab4e1" title="permalink">#</a> </h3> <p> As in the previous article, you can define a test-specific <a href="http://xunitpatterns.com/Fake%20Object.html">Fake</a> database: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">FakeDB</span>&nbsp;:&nbsp;<span style="color:#2b91af;">Collection</span>&lt;<span style="color:#2b91af;">User</span>&gt;,&nbsp;<span style="color:#2b91af;">IUserReader</span>,&nbsp;<span style="color:#2b91af;">IUserRepository</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IResult</span>&lt;<span style="color:#2b91af;">User</span>,&nbsp;<span style="color:#2b91af;">IUserLookupError</span>&gt;&nbsp;Lookup(<span style="color:blue;">string</span>&nbsp;id) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!(<span style="color:blue;">int</span>.TryParse(id,&nbsp;<span style="color:blue;">out</span>&nbsp;<span style="color:blue;">int</span>&nbsp;i))) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">Result</span>.Error&lt;<span style="color:#2b91af;">User</span>,&nbsp;<span style="color:#2b91af;">IUserLookupError</span>&gt;(<span style="color:#2b91af;">UserLookupError</span>.InvalidId); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;user&nbsp;=&nbsp;<span style="color:blue;">this</span>.FirstOrDefault(u&nbsp;=&gt;&nbsp;u.Id&nbsp;==&nbsp;i); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(user&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">Result</span>.Error&lt;<span style="color:#2b91af;">User</span>,&nbsp;<span style="color:#2b91af;">IUserLookupError</span>&gt;(<span style="color:#2b91af;">UserLookupError</span>.NotFound); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">Result</span>.Success&lt;<span style="color:#2b91af;">User</span>,&nbsp;<span style="color:#2b91af;">IUserLookupError</span>&gt;(user); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;IsDirty&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">set</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;Update(<span style="color:#2b91af;">User</span>&nbsp;user) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IsDirty&nbsp;=&nbsp;<span style="color:blue;">true</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!Contains(user)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Add(user); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> This is one of the few cases where I find inheritance more convenient than composition. By deriving from <code>Collection&lt;User&gt;</code>, you don't have to explicitly write code to expose a <em>Retrieval Interface</em>. The entirety of a standard collection API is already available via the base class. Had this class been part of a public API, I'd be concerned that inheritance could introduce future breaking changes, but as part of a suite of unit tests, I hope that I've made the right decision. </p> <p> Although you can derive a Fake database from a base class, you can still implement required interfaces - in this case <code>IUserReader</code> and <code>IUserRepository</code>. The <code>Update</code> method is the easiest one to implement, since it simply sets the <code>IsDirty</code> flag to <code>true</code> and adds the <code>user</code> if it's not already part of the collection. </p> <p> The <code>IsDirty</code> flag is the only custom Retrieval Interface added to the <code>FakeDB</code> class. As the previous article explains, this flag provides a convenient was to verify whether or not the database has changed. </p> <p> The <code>Lookup</code> method is a bit more involved, since it has to support all three outcomes implied by the protocol: <ul> <li>If the <code>id</code> is invalid, a result to that effect is returned.</li> <li>If the user isn't found, a result to that effect is returned.</li> <li>If the user with the requested <code>id</code> is found, then that user is returned.</li> </ul> This is a typical quality of a Fake: it contains <em>some</em> production-like behaviour, while still taking shortcuts compared to a full production implementation. In this case, it properly adheres to the protocol implied by the interface and protects its invariants. It still doesn't implement persistent storage, though. </p> <h3 id="92480e7451ad4c02a524f9fcd1ef1c8d"> Happy path test case <a href="#92480e7451ad4c02a524f9fcd1ef1c8d" title="permalink">#</a> </h3> <p> This is all you need in terms of <a href="http://xunitpatterns.com/Test%20Double.html">Test Doubles</a>. You now have a test-specific <code>IUserReader</code> and <code>IUserRepository</code> implementation that you can pass to the <code>Post</code> method. Notice that a single class implements multiple interfaces. This is often key to be able to implement a Fake object in the first place. </p> <p> Like in the previous article, you can start by exercising the happy path where a user successfully connects with another user: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">UserManagementTestConventions</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;UsersSuccessfullyConnect( &nbsp;&nbsp;&nbsp;&nbsp;[<span style="color:#2b91af;">Frozen</span>(<span style="color:#2b91af;">Matching</span>.ImplementedInterfaces)]<span style="color:#2b91af;">FakeDB</span>&nbsp;db, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">User</span>&nbsp;user, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">User</span>&nbsp;otherUser, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">ConnectionsController</span>&nbsp;sut) { &nbsp;&nbsp;&nbsp;&nbsp;db.Add(user); &nbsp;&nbsp;&nbsp;&nbsp;db.Add(otherUser); &nbsp;&nbsp;&nbsp;&nbsp;db.IsDirty&nbsp;=&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;sut.Post(user.Id.ToString(),&nbsp;otherUser.Id.ToString()); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;ok&nbsp;=&nbsp;<span style="color:#2b91af;">Assert</span>.IsAssignableFrom&lt;<span style="color:#2b91af;">OkNegotiatedContentResult</span>&lt;<span style="color:#2b91af;">User</span>&gt;&gt;(actual); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(otherUser,&nbsp;ok.Content); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.True(db.IsDirty); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Contains(otherUser.Id,&nbsp;user.Connections); }</pre> </p> <p> This, and all other tests in this article use <a href="https://xunit.github.io">xUnit.net</a> 2.3.1 and <a href="https://github.com/AutoFixture/AutoFixture">AutoFixture</a> 4.1.0. </p> <p> The test is organised according to my standard <a href="http://blog.ploeh.dk/2013/06/24/a-heuristic-for-formatting-code-according-to-the-aaa-pattern">heuristic for formatting tests according to the Arrange Act Assert pattern</a>. In the Arrange phase, it adds the two valid <code>User</code> objects to the Fake <code>db</code> and sets the <code>IsDirty</code> flag to false. </p> <p> Setting the flag is necessary because this is object-oriented code, where objects have mutable state. In the previous articles with examples in <a href="https://fsharp.org">F#</a> and <a href="https://www.haskell.org">Haskell</a>, the <code>User</code> types were immutable. Connecting two users didn't mutate one of the users, but rather returned a new <code>User</code> value, as this F# example demonstrates: </p> <p> <pre><span style="color:green;">//&nbsp;User&nbsp;-&gt;&nbsp;User&nbsp;-&gt;&nbsp;User</span> <span style="color:blue;">let</span>&nbsp;addConnection&nbsp;user&nbsp;otherUser&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;user&nbsp;<span style="color:blue;">with</span>&nbsp;ConnectedUsers&nbsp;=&nbsp;otherUser&nbsp;::&nbsp;user.ConnectedUsers&nbsp;}</pre> </p> <p> In the current object-oriented code base, however, connecting one user to another is an instance method on the <code>User</code> class that mutates its state: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;Connect(<span style="color:#2b91af;">User</span>&nbsp;otherUser) { &nbsp;&nbsp;&nbsp;&nbsp;connections.Add(otherUser.Id); }</pre> </p> <p> As a consequence, the <code>Post</code> method could, if someone made a mistake in its implementation, call <code>user.Connect</code>, but forget to invoke <code>UserRepository.Update</code>. Even if that happened, then all the other assertions would pass. This is the reason that you need the <code>Assert.True(db.IsDirty)</code> assertion in the Assert phase of the test. </p> <p> While we can apply to object-oriented code what we've learned from functional programming, the latter remains simpler. </p> <h3 id="011dc9e733ad44c9a656c07b2d420e1f"> Error test cases <a href="#011dc9e733ad44c9a656c07b2d420e1f" title="permalink">#</a> </h3> <p> While there's one happy path, there's four distinct error paths that you ought to cover. You can use the Fake database for that as well: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">UserManagementTestConventions</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;UsersFailToConnectWhenUserIdIsInvalid( &nbsp;&nbsp;&nbsp;&nbsp;[<span style="color:#2b91af;">Frozen</span>(<span style="color:#2b91af;">Matching</span>.ImplementedInterfaces)]<span style="color:#2b91af;">FakeDB</span>&nbsp;db, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;userId, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">User</span>&nbsp;otherUser, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">ConnectionsController</span>&nbsp;sut) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.False(<span style="color:blue;">int</span>.TryParse(userId,&nbsp;<span style="color:blue;">out</span>&nbsp;<span style="color:blue;">var</span>&nbsp;_)); &nbsp;&nbsp;&nbsp;&nbsp;db.Add(otherUser); &nbsp;&nbsp;&nbsp;&nbsp;db.IsDirty&nbsp;=&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;sut.Post(userId,&nbsp;otherUser.Id.ToString()); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;err&nbsp;=&nbsp;<span style="color:#2b91af;">Assert</span>.IsAssignableFrom&lt;<span style="color:#2b91af;">BadRequestErrorMessageResult</span>&gt;(actual); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#a31515;">&quot;Invalid&nbsp;user&nbsp;ID.&quot;</span>,&nbsp;err.Message); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.False(db.IsDirty); } [<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">UserManagementTestConventions</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;UsersFailToConnectWhenOtherUserIdIsInvalid( &nbsp;&nbsp;&nbsp;&nbsp;[<span style="color:#2b91af;">Frozen</span>(<span style="color:#2b91af;">Matching</span>.ImplementedInterfaces)]<span style="color:#2b91af;">FakeDB</span>&nbsp;db, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">User</span>&nbsp;user, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;otherUserId, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">ConnectionsController</span>&nbsp;sut) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.False(<span style="color:blue;">int</span>.TryParse(otherUserId,&nbsp;<span style="color:blue;">out</span>&nbsp;<span style="color:blue;">var</span>&nbsp;_)); &nbsp;&nbsp;&nbsp;&nbsp;db.Add(user); &nbsp;&nbsp;&nbsp;&nbsp;db.IsDirty&nbsp;=&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;sut.Post(user.Id.ToString(),&nbsp;otherUserId); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;err&nbsp;=&nbsp;<span style="color:#2b91af;">Assert</span>.IsAssignableFrom&lt;<span style="color:#2b91af;">BadRequestErrorMessageResult</span>&gt;(actual); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#a31515;">&quot;Invalid&nbsp;ID&nbsp;for&nbsp;other&nbsp;user.&quot;</span>,&nbsp;err.Message); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.False(db.IsDirty); } [<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">UserManagementTestConventions</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;UsersDoNotConnectWhenUserDoesNotExist( &nbsp;&nbsp;&nbsp;&nbsp;[<span style="color:#2b91af;">Frozen</span>(<span style="color:#2b91af;">Matching</span>.ImplementedInterfaces)]<span style="color:#2b91af;">FakeDB</span>&nbsp;db, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;userId, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">User</span>&nbsp;otherUser, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">ConnectionsController</span>&nbsp;sut) { &nbsp;&nbsp;&nbsp;&nbsp;db.Add(otherUser); &nbsp;&nbsp;&nbsp;&nbsp;db.IsDirty&nbsp;=&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;sut.Post(userId.ToString(),&nbsp;otherUser.Id.ToString()); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;err&nbsp;=&nbsp;<span style="color:#2b91af;">Assert</span>.IsAssignableFrom&lt;<span style="color:#2b91af;">BadRequestErrorMessageResult</span>&gt;(actual); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#a31515;">&quot;User&nbsp;not&nbsp;found.&quot;</span>,&nbsp;err.Message); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.False(db.IsDirty); } [<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">UserManagementTestConventions</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;UsersDoNotConnectWhenOtherUserDoesNotExist( &nbsp;&nbsp;&nbsp;&nbsp;[<span style="color:#2b91af;">Frozen</span>(<span style="color:#2b91af;">Matching</span>.ImplementedInterfaces)]<span style="color:#2b91af;">FakeDB</span>&nbsp;db, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">User</span>&nbsp;user, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;otherUserId, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">ConnectionsController</span>&nbsp;sut) { &nbsp;&nbsp;&nbsp;&nbsp;db.Add(user); &nbsp;&nbsp;&nbsp;&nbsp;db.IsDirty&nbsp;=&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;sut.Post(user.Id.ToString(),&nbsp;otherUserId.ToString()); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;err&nbsp;=&nbsp;<span style="color:#2b91af;">Assert</span>.IsAssignableFrom&lt;<span style="color:#2b91af;">BadRequestErrorMessageResult</span>&gt;(actual); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#a31515;">&quot;Other&nbsp;user&nbsp;not&nbsp;found.&quot;</span>,&nbsp;err.Message); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.False(db.IsDirty); }</pre> </p> <p> There's little to say about these tests that hasn't already been said in at least one of the previous articles. All tests inspect the state of the Fake database after calling the <code>Post</code> method. The exact interactions between <code>Post</code> and <code>db</code> aren't specified. Instead, these tests rely on setting up the initial state, exercising the SUT, and verifying the final state. These are all state-based tests that avoid over-specifying the interactions. </p> <p> Specifically, none of these tests use Mocks and Stubs. In fact, at this incarnation of the test code, I was able to entirely remove the reference to <a href="https://github.com/moq/moq4">Moq</a>. </p> <h3 id="2e73c70d74cf40dfbb3e258e4293a5cf"> Summary <a href="#2e73c70d74cf40dfbb3e258e4293a5cf" title="permalink">#</a> </h3> <p> The premise of <a href="http://amzn.to/YPdQDf">Refactoring</a> is that in order to be able to refactor, the "precondition is [...] solid tests". In reality, many development organisations have the opposite experience. When programmers attempt to make changes to how their code is organised, tests break. In <a href="http://bit.ly/xunitpatterns">xUnit Test Patterns</a> this problem is called <em>Fragile Tests</em>, and the cause is often <em>Overspecified Software</em>. This means that tests are tightly coupled to implementation details of the SUT. </p> <p> It's easy to inadvertently fall into this trap when you use Mocks and Stubs, even when you follow the rule of using <a href="http://blog.ploeh.dk/2013/10/23/mocks-for-commands-stubs-for-queries">Mocks for Commands and Stubs for Queries</a>. Refactoring tests towards state-based testing with Fake objects, instead of interaction-based testing, could make test suites more robust to changes. </p> <p> It's intriguing, though, that state-based testing is simpler in functional programming. In Haskell, you can simply write your tests in the State monad and compare the expected outcome to the actual outcome. Since state in Haskell is immutable, it's trivial to compare the expected with the actual state. </p> <p> As soon as you introduce mutable state, structural equality is no longer safe, and instead you have to rely on other inspection mechanisms, such as the <code>IsDirty</code> flag seen in this, and the previous, article. This makes the tests slightly more brittle, because it tends to pull towards interaction-based testing. </p> <p> While you can implement the State monad in both F# and C#, it's probably more pragmatic to express state-based tests using mutable state and the occasional <code>IsDirty</code> flag. As always, there's no panacea. </p> <p> While this article concludes the series on moving towards state-based testing, I think that an appendix on Test Spies is in order. </p> <p> <strong>Next:</strong> <a href="/2019/04/08/a-pure-test-spy">A pure Test Spy</a>. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="b66a6b327b8949b69db335722c9501e3"> <div class="comment-author">ladeak</div> <div class="comment-content"> <p> If we had checked the FakeDB contains to user (by retrieving, similar as in the F# case), and assert Connections property on the retrieved objects, would we still need the IsDirty flag? I think it would be good to create a couple of cases which demonstrates refactoring, and how overspecified tests break with the interaction based tests, while works nicely here. </p> </div> <div class="comment-date">2019-04-05 17:20 UTC</div> </div> <div class="comment" id="39fa5e0bfdf24153854a260addf32d0e"> <div class="comment-author"><a href="/">Mark Seemann</a></div> <div class="comment-content"> <p> ladeak, thank you for writing. The <code>IsDirty</code> flag is essentially a hack to work around the mutable nature of the <code>FakeDB</code>. As the <a href="/2019/03/25/an-example-of-state-based-testing-in-f#dd0384ed4c2d478f8374dbd55c86b197">previous article describes</a>: <blockquote> "In the previous article, the Fake database was simply an immutable dictionary. This meant that tests could easily compare expected and actual values, since they were immutable. When you use a mutable object, like the above dictionary, this is harder. Instead, what I chose to do here was to introduce an <code>IsDirty</code> flag. This enables easy verification of whether or not the database changed." </blockquote> The <a href="/2019/03/11/an-example-of-state-based-testing-in-haskell">Haskell example</a> demonstrates how no <code>IsDirty</code> flag is required, because you can simply compare the state before and after the SUT was exercised. </p> <p> You could do something similar in C# or F#, but that would require you to take an immutable snapshot of the Fake database before exercising the SUT, and then compare that snapshot with the state of the Fake database after the SUT was exercised. This is definitely also doable (as the Haskell example demonstrates), but a bit more work, which is the (unprincipled, pragmatic) reason I instead chose to use an <code>IsDirty</code> flag. </p> <p> Regarding more examples, I originally wrote another sample code base to support <a href="https://vimeo.com/296652563">this talk</a>. That sample code base contains examples that demonstrate how overspecified tests break even when you make small internal changes. I haven't yet, however, found a good home for that code base. </p> </div> <div class="comment-date">2019-04-06 10:25 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2019/04/01/an-example-of-state-based-testing-in-c An example of state based-testing in F# https://blog.ploeh.dk/2019/03/25/an-example-of-state-based-testing-in-f/ Mon, 25 Mar 2019 06:34:00 UTC <div id="post"> <p> <em>While F# is a functional-first language, it's okay to occasionally be pragmatic and use mutable state, for example to easily write some sustainable state-based tests.</em> </p> <p> This article is an instalment in an article series about how to move <a href="/2019/02/18/from-interaction-based-to-state-based-testing">from interaction-based testing to state-based testing</a>. In the previous article, you saw how to write <a href="/2019/03/11/an-example-of-state-based-testing-in-haskell">state-based tests in Haskell</a>. In this article, you'll see how to apply what you've learned in <a href="https://fsharp.org">F#</a>. </p> <p> The code shown in this article is <a href="https://github.com/ploeh/UserManagement">available on GitHub</a>. </p> <h3 id="57929a79c0a740c5986df12fc6e4b1c1"> A function to connect two users <a href="#57929a79c0a740c5986df12fc6e4b1c1" title="permalink">#</a> </h3> <p> This article, like the others in this series, implements an operation to connect two users. I explain the example in details in my two <a href="https://cleancoders.com">Clean Coders</a> videos, <a href="https://cleancoders.com/episode/humane-code-real-episode-4/show">Church Visitor</a> and <a href="https://cleancoders.com/episode/humane-code-real-episode-5/show">Preserved in translation</a>. </p> <p> Like in the previous <a href="https://www.haskell.org">Haskell</a> example, in this article we'll start with the implementation, and then see how to unit test it. </p> <p> <pre><span style="color:green;">//&nbsp;(&#39;a&nbsp;-&gt;&nbsp;Result&lt;User,UserLookupError&gt;)&nbsp;-&gt;&nbsp;(User&nbsp;-&gt;&nbsp;unit)&nbsp;-&gt;&nbsp;&#39;a&nbsp;-&gt;&nbsp;&#39;a&nbsp;-&gt;&nbsp;HttpResponse&lt;User&gt;</span> <span style="color:blue;">let</span>&nbsp;post&nbsp;lookupUser&nbsp;updateUser&nbsp;userId&nbsp;otherUserId&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;userRes&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;lookupUser&nbsp;userId&nbsp;|&gt;&nbsp;Result.mapError&nbsp;(<span style="color:blue;">function</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;InvalidId&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#a31515;">&quot;Invalid&nbsp;user&nbsp;ID.&quot;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;NotFound&nbsp;&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#a31515;">&quot;User&nbsp;not&nbsp;found.&quot;</span>) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;otherUserRes&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;lookupUser&nbsp;otherUserId&nbsp;|&gt;&nbsp;Result.mapError&nbsp;(<span style="color:blue;">function</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;InvalidId&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#a31515;">&quot;Invalid&nbsp;ID&nbsp;for&nbsp;other&nbsp;user.&quot;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;NotFound&nbsp;&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#a31515;">&quot;Other&nbsp;user&nbsp;not&nbsp;found.&quot;</span>) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;connect&nbsp;=&nbsp;result&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;user&nbsp;=&nbsp;userRes &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;otherUser&nbsp;=&nbsp;otherUserRes &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;addConnection&nbsp;user&nbsp;otherUser&nbsp;|&gt;&nbsp;updateUser &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;otherUser&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;connect&nbsp;<span style="color:blue;">with</span>&nbsp;Ok&nbsp;u&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;OK&nbsp;u&nbsp;|&nbsp;Error&nbsp;msg&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;BadRequest&nbsp;msg</pre> </p> <p> While <a href="/2019/02/25/an-example-of-interaction-based-testing-in-c">the original C# example</a> used Constructor Injection, the above <code>post</code> function uses <a href="/2017/01/30/partial-application-is-dependency-injection">partial application for Dependency Injection</a>. The two function arguments <code>lookupUser</code> and <code>updateUser</code> represent interactions with a database. Since functions are polymorphic, however, it's possible to replace them with <a href="http://xunitpatterns.com/Test%20Double.html">Test Doubles</a>. </p> <h3 id="dd0384ed4c2d478f8374dbd55c86b197"> A Fake database <a href="#dd0384ed4c2d478f8374dbd55c86b197" title="permalink">#</a> </h3> <p> Like in the Haskell example, you can implement a <a href="http://xunitpatterns.com/Fake%20Object.html">Fake</a> database in F#. It's also possible to implement the State monad in F#, but there's less need for it. F# is a functional-first language, but you can also write mutable code if need be. You could, then, choose to be pragmatic and base your Fake database on mutable state. </p> <p> <pre><span style="color:blue;">type</span>&nbsp;FakeDB&nbsp;()&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;users&nbsp;=&nbsp;Dictionary&lt;int,&nbsp;User&gt;&nbsp;() &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">member</span>&nbsp;<span style="color:blue;">val</span>&nbsp;IsDirty&nbsp;=&nbsp;<span style="color:blue;">false</span>&nbsp;<span style="color:blue;">with</span>&nbsp;get,&nbsp;set &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">member</span>&nbsp;this.AddUser&nbsp;user&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.IsDirty&nbsp;<span style="color:blue;">&lt;-</span>&nbsp;<span style="color:blue;">true</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;users.Add&nbsp;(user.UserId,&nbsp;user) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">member</span>&nbsp;this.TryFind&nbsp;i&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;users.TryGetValue&nbsp;i&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:blue;">false</span>,&nbsp;_&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;None &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:blue;">true</span>,&nbsp;&nbsp;u&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;Some&nbsp;u &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">member</span>&nbsp;this.LookupUser&nbsp;s&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;Int32.TryParse&nbsp;s&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:blue;">false</span>,&nbsp;_&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;Error&nbsp;InvalidId &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:blue;">true</span>,&nbsp;i&nbsp;<span style="color:blue;">-&gt;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;users.TryGetValue&nbsp;i&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:blue;">false</span>,&nbsp;_&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;Error&nbsp;NotFound &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:blue;">true</span>,&nbsp;u&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;Ok&nbsp;u &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">member</span>&nbsp;this.UpdateUser&nbsp;u&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.IsDirty&nbsp;<span style="color:blue;">&lt;-</span>&nbsp;<span style="color:blue;">true</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;users.[u.UserId]&nbsp;<span style="color:blue;">&lt;-</span>&nbsp;u</pre> </p> <p> This <code>FakeDB</code> type is <em>a class</em> that wraps a mutable dictionary. While it 'implements' <code>LookupUser</code> and <code>UpdateUser</code>, it also exposes what <a href="http://bit.ly/xunitpatterns">xUnit Test Patterns</a> calls a <em>Retrieval Interface:</em> an API that tests can use to examine the state of the object. </p> <p> Immutable values normally have structural equality. This means that two values are considered equal if they contain the same constituent values, and have the same structure. Mutable objects, on the other hand, typically have reference equality. This makes it harder to compare two objects, which is, however, what almost all unit testing is about. You compare expected state with actual state. </p> <p> In the previous article, the Fake database was simply an immutable dictionary. This meant that tests could easily compare expected and actual values, since they were immutable. When you use a mutable object, like the above dictionary, this is harder. Instead, what I chose to do here was to introduce an <code>IsDirty</code> flag. This enables easy verification of whether or not the database changed. </p> <h3 id="88dbfa0dd8f34f4ba91f2b7acc6173b1"> Happy path test case <a href="#88dbfa0dd8f34f4ba91f2b7acc6173b1" title="permalink">#</a> </h3> <p> This is all you need in terms of Test Doubles. You now have test-specific <code>LookupUser</code> and <code>UpdateUser</code> methods that you can pass to the <code>post</code> function. </p> <p> Like in the previous article, you can start by exercising the happy path where a user successfully connects with another user: </p> <p> <pre>[&lt;Fact&gt;] <span style="color:blue;">let</span>&nbsp;``Users&nbsp;successfully&nbsp;connect``&nbsp;()&nbsp;=&nbsp;Property.check&nbsp;&lt;|&nbsp;property&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;user&nbsp;=&nbsp;Gen.user &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;otherUser&nbsp;=&nbsp;Gen.withOtherId&nbsp;user &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;db&nbsp;=&nbsp;FakeDB&nbsp;() &nbsp;&nbsp;&nbsp;&nbsp;db.AddUser&nbsp;user &nbsp;&nbsp;&nbsp;&nbsp;db.AddUser&nbsp;otherUser &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;actual&nbsp;=&nbsp;post&nbsp;db.LookupUser&nbsp;db.UpdateUser&nbsp;(string&nbsp;user.UserId)&nbsp;(string&nbsp;otherUser.UserId) &nbsp;&nbsp;&nbsp;&nbsp;test&nbsp;&lt;@&nbsp;db.TryFind&nbsp;user.UserId &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&gt;&nbsp;Option.exists &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(<span style="color:blue;">fun</span>&nbsp;u&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;u.ConnectedUsers&nbsp;|&gt;&nbsp;List.contains&nbsp;otherUser)&nbsp;@&gt; &nbsp;&nbsp;&nbsp;&nbsp;test&nbsp;&lt;@&nbsp;isOK&nbsp;actual&nbsp;@&gt;&nbsp;}</pre> </p> <p> All tests in this article use <a href="https://xunit.github.io">xUnit.net</a> 2.3.1, <a href="https://github.com/SwensenSoftware/unquote">Unquote</a> 4.0.0, and <a href="https://github.com/hedgehogqa/fsharp-hedgehog">Hedgehog</a> 0.7.0.0. </p> <p> This test first adds two valid users to the Fake database <code>db</code>. It then calls the <code>post</code> function, passing the <code>db.LookupUser</code> and <code>db.UpdateUser</code> methods as arguments. Finally, it verifies that the 'first' user's <code>ConnectedUsers</code> now contains the <code>otherUser</code>. It also verifies that <code>actual</code> represents a <code>200 OK</code> HTTP response. </p> <h3 id="750f435b6e854db898e0da44119ee4f6"> Missing user test case <a href="#750f435b6e854db898e0da44119ee4f6" title="permalink">#</a> </h3> <p> While there's one happy-path test case, there's four other test cases left. One of these is when the first user doesn't exist: </p> <p> <pre>[&lt;Fact&gt;] <span style="color:blue;">let</span>&nbsp;``Users&nbsp;don&#39;t&nbsp;connect&nbsp;when&nbsp;user&nbsp;doesn&#39;t&nbsp;exist``&nbsp;()&nbsp;=&nbsp;Property.check&nbsp;&lt;|&nbsp;property&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;i&nbsp;=&nbsp;Range.linear&nbsp;1&nbsp;1_000_000&nbsp;|&gt;&nbsp;Gen.int &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;otherUser&nbsp;=&nbsp;Gen.user &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;db&nbsp;=&nbsp;FakeDB&nbsp;() &nbsp;&nbsp;&nbsp;&nbsp;db.AddUser&nbsp;otherUser &nbsp;&nbsp;&nbsp;&nbsp;db.IsDirty&nbsp;<span style="color:blue;">&lt;-</span>&nbsp;<span style="color:blue;">false</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;uniqueUserId&nbsp;=&nbsp;string&nbsp;(otherUser.UserId&nbsp;+&nbsp;i) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;actual&nbsp;=&nbsp;post&nbsp;db.LookupUser&nbsp;db.UpdateUser&nbsp;uniqueUserId&nbsp;(string&nbsp;otherUser.UserId) &nbsp;&nbsp;&nbsp;&nbsp;test&nbsp;&lt;@&nbsp;not&nbsp;db.IsDirty&nbsp;@&gt; &nbsp;&nbsp;&nbsp;&nbsp;test&nbsp;&lt;@&nbsp;isBadRequest&nbsp;actual&nbsp;@&gt;&nbsp;}</pre> </p> <p> This test adds one valid user to the Fake database. Once it's done with configuring the database, it sets <code>IsDirty</code> to <code>false</code>. The <code>AddUser</code> method sets <code>IsDirty</code> to <code>true</code>, so it's important to reset the flag before the <em>act</em> phase of the test. You could consider this a bit of a hack, but I think it makes the intent of the test clear. This is, however, a position I'm ready to reassess should the tests evolve to make this design awkward. </p> <p> As explained in the previous article, this test case requires an ID of a user that doesn't exist. Since this is a property-based test, there's a risk that Hedgehog might generate a number <code>i</code> equal to <code>otherUser.UserId</code>. One way to get around that problem is to add the two numbers together. Since <code>i</code> is generated from the range <em>1 - 1,000,000</em>, <code>uniqueUserId</code> is guaranteed to be different from <code>otherUser.UserId</code>. </p> <p> The test verifies that the state of the database didn't change (that <code>IsDirty</code> is still <code>false</code>), and that <code>actual</code> represents a <code>400 Bad Request</code> HTTP response. </p> <h3 id="4dbe21251f8440b1a594192d07b53c9f"> Remaining test cases <a href="#4dbe21251f8440b1a594192d07b53c9f" title="permalink">#</a> </h3> <p> You can write the remaining three test cases in the same vein: </p> <p> <pre>[&lt;Fact&gt;] <span style="color:blue;">let</span>&nbsp;``Users&nbsp;don&#39;t&nbsp;connect&nbsp;when&nbsp;other&nbsp;user&nbsp;doesn&#39;t&nbsp;exist``&nbsp;()&nbsp;=&nbsp;Property.check&nbsp;&lt;|&nbsp;property&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;i&nbsp;=&nbsp;Range.linear&nbsp;1&nbsp;1_000_000&nbsp;|&gt;&nbsp;Gen.int &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;user&nbsp;=&nbsp;Gen.user &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;db&nbsp;=&nbsp;FakeDB&nbsp;() &nbsp;&nbsp;&nbsp;&nbsp;db.AddUser&nbsp;user &nbsp;&nbsp;&nbsp;&nbsp;db.IsDirty&nbsp;<span style="color:blue;">&lt;-</span>&nbsp;<span style="color:blue;">false</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;uniqueOtherUserId&nbsp;=&nbsp;string&nbsp;(user.UserId&nbsp;+&nbsp;i) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;actual&nbsp;=&nbsp;post&nbsp;db.LookupUser&nbsp;db.UpdateUser&nbsp;(string&nbsp;user.UserId)&nbsp;uniqueOtherUserId&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;test&nbsp;&lt;@&nbsp;not&nbsp;db.IsDirty&nbsp;@&gt; &nbsp;&nbsp;&nbsp;&nbsp;test&nbsp;&lt;@&nbsp;isBadRequest&nbsp;actual&nbsp;@&gt;&nbsp;} [&lt;Fact&gt;] <span style="color:blue;">let</span>&nbsp;``Users&nbsp;don&#39;t&nbsp;connect&nbsp;when&nbsp;user&nbsp;Id&nbsp;is&nbsp;invalid``&nbsp;()&nbsp;=&nbsp;Property.check&nbsp;&lt;|&nbsp;property&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;s&nbsp;=&nbsp;Gen.alphaNum&nbsp;|&gt;&nbsp;Gen.string&nbsp;(Range.linear&nbsp;0&nbsp;100)&nbsp;|&gt;&nbsp;Gen.filter&nbsp;isIdInvalid &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;otherUser&nbsp;=&nbsp;Gen.user &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;db&nbsp;=&nbsp;FakeDB&nbsp;() &nbsp;&nbsp;&nbsp;&nbsp;db.AddUser&nbsp;otherUser &nbsp;&nbsp;&nbsp;&nbsp;db.IsDirty&nbsp;<span style="color:blue;">&lt;-</span>&nbsp;<span style="color:blue;">false</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;actual&nbsp;=&nbsp;post&nbsp;db.LookupUser&nbsp;db.UpdateUser&nbsp;s&nbsp;(string&nbsp;otherUser.UserId) &nbsp;&nbsp;&nbsp;&nbsp;test&nbsp;&lt;@&nbsp;not&nbsp;db.IsDirty&nbsp;@&gt; &nbsp;&nbsp;&nbsp;&nbsp;test&nbsp;&lt;@&nbsp;isBadRequest&nbsp;actual&nbsp;@&gt;&nbsp;} [&lt;Fact&gt;] <span style="color:blue;">let</span>&nbsp;``Users&nbsp;don&#39;t&nbsp;connect&nbsp;when&nbsp;other&nbsp;user&nbsp;Id&nbsp;is&nbsp;invalid``&nbsp;()&nbsp;=&nbsp;Property.check&nbsp;&lt;|&nbsp;property&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;s&nbsp;=&nbsp;Gen.alphaNum&nbsp;|&gt;&nbsp;Gen.string&nbsp;(Range.linear&nbsp;0&nbsp;100)&nbsp;|&gt;&nbsp;Gen.filter&nbsp;isIdInvalid &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;user&nbsp;=&nbsp;Gen.user &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;db&nbsp;=&nbsp;FakeDB&nbsp;() &nbsp;&nbsp;&nbsp;&nbsp;db.AddUser&nbsp;user &nbsp;&nbsp;&nbsp;&nbsp;db.IsDirty&nbsp;<span style="color:blue;">&lt;-</span>&nbsp;<span style="color:blue;">false</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;actual&nbsp;=&nbsp;post&nbsp;db.LookupUser&nbsp;db.UpdateUser&nbsp;(string&nbsp;user.UserId)&nbsp;s &nbsp;&nbsp;&nbsp;&nbsp;test&nbsp;&lt;@&nbsp;not&nbsp;db.IsDirty&nbsp;@&gt; &nbsp;&nbsp;&nbsp;&nbsp;test&nbsp;&lt;@&nbsp;isBadRequest&nbsp;actual&nbsp;@&gt;&nbsp;}</pre> </p> <p> All tests inspect the state of the Fake database after the calling the <code>post</code> function. The exact interactions between <code>post</code> and <code>db</code> aren't specified. Instead, these tests rely on setting up the initial state, exercising the System Under Test, and verifying the final state. These are all state-based tests that avoid over-specifying the interactions. </p> <h3 id="102ff7e3a9b247b4914f113b06afd6df"> Summary <a href="#102ff7e3a9b247b4914f113b06afd6df" title="permalink">#</a> </h3> <p> While the previous Haskell example demonstrated that it's possible to write state-based unit tests in a functional style, when using F#, it sometimes make sense to leverage the object-oriented features already available in the .NET framework, such as mutable dictionaries. It would have been possible to write purely functional state-based tests in F# as well, by porting the Haskell examples, but here, I wanted to demonstrate that this isn't required. </p> <p> I tend to be of the opinion that it's only possible to be pragmatic if you know how to be dogmatic, but now that we know how to write state-based tests in a strictly functional style, I think it's fine to be pragmatic and use a bit of mutable state in F#. The benefit of this is that it now seems clear how to apply what we've learned to the original C# example. </p> <p> <strong>Next: </strong> <a href="/2019/04/01/an-example-of-state-based-testing-in-c">An example of state-based testing in C#</a>. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2019/03/25/an-example-of-state-based-testing-in-f The programmer as decision maker https://blog.ploeh.dk/2019/03/18/the-programmer-as-decision-maker/ Mon, 18 Mar 2019 07:44:00 UTC <div id="post"> <p> <em>As a programmer, your job is to make technical decisions. Make some more.</em> </p> <p> When <a href="/schedule">I speak at conferences</a>, people often come and talk to me. (I welcome that, BTW.) Among all the conversations I've had over the years, there's a pattern to some of them. The attendee will start by telling me how inspired (s)he is by the talk I just gave, or something I've written. That's gratifying, and a good way to start a conversation, but is often followed up like this: </p> <p> <strong>Attendee:</strong> "I just wish that we could do something like that in our organisation..." </p> <p> Let's just say that here we're talking about test-driven development, or perhaps just unit testing. Nothing too controversial. I'd typically respond, </p> <p> <strong>Me:</strong> "Why can't you?" </p> <p> <strong>Attendee:</strong> "Our boss won't let us..." </p> <p> That's unfortunate. If your boss has explicitly forbidden you to write and run unit tests, then there's not much you can do. Let me make this absolutely clear: I'm not going on record saying that you should actively disobey a direct order (unless it's unethical, that is). I do wonder, however: </p> <p> <em>Why is the boss even involved in that decision?</em> </p> <p> It seems to me that programmers often defer too much authority to their managers. </p> <h3 id="510367ded1ca47e7922b540d2fff50b0"> A note on culture <a href="#510367ded1ca47e7922b540d2fff50b0" title="permalink">#</a> </h3> <p> I'd like to preface the rest of this article with my own context. I've spent most of my programming career in Danish organisations. Even when I worked for Microsoft, I worked for Danish subsidiaries, with Danish managers. </p> <p> The power distance in Denmark is (in)famously short. It's not unheard of for individual contributors to question their superiors' decisions; sometimes to their face, and sometimes even when other people witness this. When done respectfully (which it often is), this can be extremely efficient. Managers are as fallible as the rest of us, and often their subordinates know of details that could impact a decision that a manager is about to make. Immediately discussing such details can help ensure that good decisions are made, and bad decisions are cancelled. </p> <p> This helps managers make better decisions, so enlightened managers welcome feedback. </p> <p> In general, Danish employees also tend to have a fair degree of autonomy. What I'll suggest in this article is unlikely to get you fired in Denmark. Please use your own judgement if you consider transplanting the following to your own culture. </p> <h3 id="eaa896ed8a6240729301c54fed859ab7"> Technical decisions <a href="#eaa896ed8a6240729301c54fed859ab7" title="permalink">#</a> </h3> <p> If your job is <em>programmer</em>, <em>software developer</em>, or similar, the value you add to the team is that you bring <em>technical expertise</em>. Maybe some of your colleagues are programmers as well, but together, you are the people with the technical expertise. </p> <p> Even if the project manager or other superiors used to program, unless they're also writing code for the current code base, they only have general technical expertise, but not specific expertise related to the code base you're working with. The people with most technical expertise are you and your colleagues. </p> <p> You are decision makers. </p> <p> Whenever you interact with your code base, you make technical decisions. </p> <p> In order to handle incoming HTTP requests to a <code>/reservations</code> resource, you may first decide to create a <a href="/2019/02/11/asynchronous-injection">new file called <code>ReservationsController.cs</code></a>. You'd most likely also decide to open that file and start adding code to it. </p> <p> Perhaps you add a method called <code>Post</code> that takes a <code>Reservation</code> argument. Perhaps you decide to inject an <code>IMaîtreD</code> dependency. </p> <p> At various steps along the way, you may decide to compile the code. </p> <p> Once you think that you've made enough changes to address your current work item, you may decide to run the program to see if it works. For a web-based piece of software, that typically involves starting up a browser and somehow interacting with the service. If your program is a web site, you may start at the front page, log in, click around, and fill in some forms. If your program is a REST API, you may interact with it via Fiddler or Postman (I prefer curl or <a href="https://github.com/ploeh/Furl">Furl</a>, but most people I've met still prefer something they can click on, it seems). </p> <p> What often happens is that your changes don't work the first time around, so you'll have to troubleshoot. Perhaps you decide to use a debugger. </p> <p> How many decisions are that? </p> <p> I just described seven or eight types of the sort of decisions you make as a programmer. You make such decisions all the time. Do you ask your managers permission before you start a debugging session? Before you create a new file? Before you name a variable? </p> <p> Of course you don't. You're the technical expert. There's no-one better equipped than you or your team members to make those decisions. </p> <h3 id="bed169525ccf4a90aaa9c0e33fcbf8d0"> Decide to add unit tests <a href="#bed169525ccf4a90aaa9c0e33fcbf8d0" title="permalink">#</a> </h3> <p> If you want to add unit tests, why don't you just decide to add them? If you want to apply test-driven development, why don't you just do so? </p> <p> A unit test is one or more code files. You're already authorised to make decisions about adding files. </p> <p> You can run a test suite instead of launching the software every time you want to interact with it. It's likely to be faster, even. </p> <p> Why should you ask permission to do that? </p> <h3 id="e42aac76e52141e68a0bc08fefa56a9b"> Decide to refactor <a href="#e42aac76e52141e68a0bc08fefa56a9b" title="permalink">#</a> </h3> <p> Another complaint I hear is that people aren't allowed to refactor. </p> <p> Why are you even asking permission to refactor? </p> <p> <a href="http://amzn.to/YPdQDf">Refactoring</a> means reorganising the code without changing the behaviour of the system. Another word for that is <em>editing</em> the code. It's okay. You're already permitted to edit code. It's part of your job description. </p> <p> I think I know what the underlying problem is, though... </p> <h3 id="f8c290ef29bd437daf2a81b3e06e131c"> Make technical decisions in the small <a href="#f8c290ef29bd437daf2a81b3e06e131c" title="permalink">#</a> </h3> <p> As an individual contributor, you're empowered to make small-scale technical decisions. These are decisions that are unlikely to impact schedules or allocation of programmers, including new hires. Big decisions probably should involve your manager. </p> <p> I have an inkling of why people feel that they need permission to refactor. It's because the refactoring they have in mind is going to take weeks. Weeks in which nothing else can be done. Weeks where perhaps the code doesn't even compile. </p> <p> Many years ago (but not as many as I'd like it to be), my colleague and I had what Eric Evans in <a href="http://amzn.to/WBCwx7">DDD</a> calls a <em>breakthrough</em>. We wanted to refactor towards deeper insight. What prompted the insight was a new feature that we had to add, and we'd been throwing design ideas back and forth for some time before the new insight arrived. </p> <p> We could implement the new feature if we changed one of the core abstractions in our domain model, but it required substantial changes to the existing code base. We informed our manager of our new insight and our plan, estimating that it would take less than a week to make the changes and implement the new feature. Our manager agreed with the plan. </p> <p> Two weeks later our code hadn't been in a compilable state for a week. Our manager pulled me away to tell me, quietly and equitably, that he was not happy with our lack of progress. I could only concur. </p> <p> After more heroic work, we finally managed to complete the changes and implement the new feature. Nonetheless, blocking all other development for two-three weeks in order to make a change isn't acceptable. </p> <p> That sort of change is a big decision because it impacts other team members, schedules, and perhaps overall business plans. Don't make those kinds of decisions without consulting with stakeholders. </p> <p> This still leaves, I believe, lots of room for individual decision-making in the small. What I learned from the experience I just recounted was not to engage in big changes to a code base. Learn how to make multiple incremental changes instead. In case that's completely impossible, add the new model side-by-side with the old model, and incrementally change over. That's what I should have done those many years ago. </p> <h3 id="298ca23885544e5f906379c1a6d15586"> Don't be sneaky <a href="#298ca23885544e5f906379c1a6d15586" title="permalink">#</a> </h3> <p> When I give talks about the blessings of functional programming, I sometimes get into another type of discussion. </p> <p> <strong>Attendee:</strong> It's so inspiring how beautiful and simple complex domain models become in <a href="https://fsharp.org">F#</a>. How can we do the same in C#? </p> <p> <strong>Me:</strong> You can't. If you're already using C#, you should strongly consider F# if you wish to do functional programming. Since it's also a .NET language, you can gradually introduce F# code and mix the compiled code with your existing C# code. </p> <p> <strong>Attendee:</strong> Yes... [already getting impatient with me] But we can't do that... </p> <p> <strong>Me:</strong> Why not? </p> <p> <strong>Attendee:</strong> Because our manager will not allow it. </p> <p> Based on the suggestions I've already made here, you may expect me to say that that's another technical decision that you should make without asking permission. Like the previous example about blocking refactorings, however, this is another large-scale decision. </p> <p> Your manager may be concerned that it'd be hard to find new employees if the code base is written in some niche language. <a href="/2015/12/03/the-rules-of-attraction-language">I tend to disagree with that position</a>, but I do understand why a manager would take that position. While I think it suboptimal to restrict an entire development organisation to a single language (whether it's C#, Java, C++, Ruby, etc.), I'll readily accept that language choice is a strategic decision. </p> <p> If every programmer got to choose the programming language they prefer the most that day, you'd have code bases written in dozens of different languages. While you can train bright new hires to learn a new language or two, it's unrealistic that a new employee will be able to learn thirty different languages in a short while. </p> <p> I find it reasonable that a manager has the final word on the choice of language, even when I often disagree with the decisions. </p> <p> The outcome usually is that people are stuck with C# (or Java, or...). Hence the question: <em>How can we do functional programming in C#?</em> </p> <p> I'll give the answer that I often give here on the blog: <a href="https://en.wikipedia.org/wiki/Mu_(negative)">mu</a> (<em>unask the question</em>). You can, in fact, translate functional concepts to C#, but <a href="/2018/07/24/dependency-injection-revisited">the result is so non-idiomatic</a> that only the syntax remains of C#: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;Select&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;source, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;selector) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;source.Match&lt;<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;isReservationInFuture:&nbsp;t&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">IsReservationInFuture</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">Reservation</span>,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">bool</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.Item1, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;b&nbsp;=&gt;&nbsp;selector(t.Item2(b)))), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;readReservations:&nbsp;t&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ReadReservations</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">DateTimeOffset</span>,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.Item1, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;d&nbsp;=&gt;&nbsp;selector(t.Item2(d)))), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;create:&nbsp;t&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Create</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">Reservation</span>,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.Item1, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;r&nbsp;=&gt;&nbsp;selector(t.Item2(r))))); }</pre> </p> <p> Keep in mind the manager's motivation for standardising on C#. It's often related to concerns about being able to hire new employees, or move employees from project to project. </p> <p> If you write 'functional' C#, you'll end up with code like the above, or the following real-life example: </p> <p> <pre><span style="color:blue;">return</span>&nbsp;<span style="color:blue;">await</span>&nbsp;sendRequest( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">ApiMethodNames</span>.InitRegistration, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">GSObject</span>()) &nbsp;&nbsp;&nbsp;&nbsp;.Map(r&nbsp;=&gt;&nbsp;<span style="color:#2b91af;">ValidateResponse</span>.Validate(r) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.MapFailure(_&nbsp;=&gt;&nbsp;<span style="color:#2b91af;">ErrorResponse</span>.RegisterErrorResponse())) &nbsp;&nbsp;&nbsp;&nbsp;.Bind(r&nbsp;=&gt;&nbsp;r.RetrieveField(<span style="color:#a31515;">&quot;regToken&quot;</span>)) &nbsp;&nbsp;&nbsp;&nbsp;.BindAsync(token&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sendRequest( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">ApiMethodNames</span>.RegisterAccount, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CreateRegisterRequest( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mailAddress, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;password, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;token)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Map(<span style="color:#2b91af;">ValidateResponse</span>.Validate) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Bind(response&nbsp;=&gt;&nbsp;getIdentity(response) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.ToResult(<span style="color:#2b91af;">ErrorResponse</span>.ExternalServiceResponseInvalid))) &nbsp;&nbsp;&nbsp;&nbsp;.Map(id&nbsp;=&gt;&nbsp;<span style="color:#2b91af;">GigyaIdentity</span>.CreateNewSiteUser(id.UserId,&nbsp;mailAddress));</pre> </p> <p> (I'm indebted to <a href="https://twitter.com/runeibsen">Rune Ibsen</a> for this example.) </p> <p> A new hire can have ten years of C# experience and still have no chance in a code base like that. You'll first have to teach him or her functional programming. If you can do that, you might as well also teach a new language, like F#. </p> <p> It's my experience that learning the syntax of a new language is easy, and usually doesn't take much time. The hard part is learning a new way to think. </p> <p> Writing 'functional' C# makes it doubly hard on new team members. Not only do they have to learn a new paradigm (functional programming), but they have to learn it in a language unsuited for that paradigm. </p> <p> That's why I think you should unask the question. If your manager doesn't want to allow F#, then writing 'functional' C# is just being sneaky. That'd be obeying the letter of the law while breaking the spirit of it. That is, in my opinion, immoral. Don't be sneaky. </p> <h3 id="2f1b38953bbc4814994ee471caf4c5ac"> Summary <a href="#2f1b38953bbc4814994ee471caf4c5ac" title="permalink">#</a> </h3> <p> As a professional programmer, your job is to be a technical expert. In normal circumstances (at least the ones I know from my own career), you have agency. In order to get anything done, you make small decisions all the time, such as editing code. That's not only okay, but expected of you. </p> <p> Some decision, on the other hand, can have substantial ramifications. Choosing to write code in an unsanctioned language tends to fall on the side where a manager should be involved in the decision. </p> <p> In between is a grey area. </p> <p> <img src="/content/binary/small-vs-big-decisions-gradient.png" alt="A spectrum of decisions from small to the left to big to the right."> </p> <p> I don't even consider adding unit tests to be in the grey area, but some refactorings may be. <blockquote> <p>"It's easier to ask forgiveness than it is to get permission."</p> <footer><cite>Grace Hopper</cite></footer> </blockquote> </p> <p> To navigate grey areas you need a moral compass. </p> <p> I'll let you be the final judge of what you can get away with, but I consider it both appropriate and ethical to make the decision to add unit tests, and to continually improve code bases. You shouldn't have to ask permission to do that. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="dd2ab8d5dc6e4c5f9e49d7d7f35a8759"> <div class="comment-author"><a href="https://github.com/chicocode">Francisco Berrocal</a></div> <div class="comment-content"> <p>Before all, I'd just like to thank all the content you share, they all make me think in a good way!</p> <p> Now regarding to this post, while I tend to agree that a developer can take the decision to add (or not) unit tests by himself, there is no great value comming out of it, if that's not an approach of the whole development team, right? I believe we need the entire team on board to maximize the values of unit tests. There are changes we need to consider, from changes in the mindset of how you develop to actually running them on continuour integration pipelines. Doesn't all of that push simple decisions like "add unit test" from green area towards orange area? </p> </div> <div class="comment-date">2019-03-18 13:14 UTC</div> </div> <div class="comment" id="2bc69a5123d8499ca40631b9ce946919"> <div class="comment-author"><a href="/">Mark Seemann</a></div> <div class="comment-content"> <p> Francisco, thank you for writing. If you have a team of developers, then I agree that unit tests are going to be most valuable if the team decides to use them. </p> <p> This is still something that you ought to be competent to decide as a self-organising team of developers. Do you need to ask a manager's permission? </p> <p> I'm not trying to pretend that this is easy. I realise that it can be difficult. </p> <p> I've heard about teams where other developers are hostile to the idea of unit testing. In that situation, I can offer no easy fixes. What a lone developer can try to do in that situation is to add and run unit tests locally, on his or her own machine. This will incur some friction, because other team members will be oblivious to the tests, so they'll change code that will cause those unit tests to break. </p> <p> This might teach the lone developer to write tests so that they're as robust to trivial changes as possible. That's a valuable skill in any case. There's still going to be some overhead of maintaining the unit tests in a scenario like that, but if that overhead is smaller than the productivity gained, then in might still be worthwhile. </p> <p> What might then happen could be that other developers who are on the fence see that the lone unit tester is more effective than they are. Perhaps they'll get curious about unit tests after all, once they can see the contours of advantages. </p> <p> The next scenario, then, is a team with a few developers writing unit tests, and other who don't. At some number, you'll have achieved enough critical mass that, at least, you get to check in the unit tests together with the source code. Soon after, you may be able to institute a policy that while not everyone writes unit tests, it's not okay to break existing tests. </p> <p> The next thing you can do, then, is to set up a test run as part of continuous integration and declare that a failing test run means that the build broke. You still have team members who don't write tests, but at least you get to do it, and the tests add value to the whole team. </p> <p> Perhaps the sceptics will slowly start to write unit tests over time. Some die-hards probably never will. </p> <p> You may be able to progress through such stages without asking a manager, but I do understand that there's much variation in organisation and team dynamics. If you can use any of the above sketches as inspiration, then that's great. If you (or other readers) have other success stories to tell, then please share them. </p> <p> The point I was trying to make with this article is that programmers have agency. This isn't a licence to do whatever you please. You still have to navigate the dynamics of whatever organisation you're in. You may not, however, need to ask your manager about every little thing that you're competent to decide yourselves. </p> </div> <div class="comment-date">2019-03-19 7:57 UTC</div> </div> <div class="comment"> <div class="comment-author"><a href="https://hettomei.github.io/">Timothée GAUTHIER</a></div> <div class="comment-content"> <p> Thank you A LOT for putting words on all these thought. You'll be my reference whenever I want to introduce unit test. </p> <p> My usual example is "a surgeon doesn't need to ask to the manager if he can wash his hand. Whashing his hand is part of his job". (Not mine, but I can't remember where it comes from) </p> </div> <div class="comment-date">2019-03-19 20:15 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2019/03/18/the-programmer-as-decision-maker