ploeh blog 2018-09-23T14:22:38+00:00 Mark Seemann danish software design http://blog.ploeh.dk Typing is not a programming bottleneck http://blog.ploeh.dk/2018/09/17/typing-is-not-a-programming-bottleneck 2018-09-17T08:16:00+00:00 Mark Seemann <div id="post"> <p> <em>Some developers seem to think that typing is a major bottleneck while programming. It's not.</em> </p> <p> I sometimes give programming advice to people. They approach me with a software design problem, and, to the best of my ability, I suggest a remedy. Despite my best intentions, my suggestions sometimes meet resistance. One common reaction is that <a href="http://blog.ploeh.dk/2015/08/03/idiomatic-or-idiosyncratic">my suggestion isn't idiomatic</a>, but recently, another type of criticism seems to be on the rise. </p> <p> The code that I suggest is too verbose. It involves too much typing. </p> <p> I'll use this article to reflect on that criticism. </p> <h3 id="d1f8398f96584ed09acce1b481b45cde"> The purpose of code <a href="#d1f8398f96584ed09acce1b481b45cde" title="permalink">#</a> </h3> <p> Before we get into the details of the issue, I'd like to start with the big picture. What's the purpose of code? </p> <p> I've discussed this extensively in my <a href="https://cleancoders.com">Clean Coders</a> video on <a href="https://cleancoders.com/episode/humane-code-real-episode-1/show">Humane Code</a>. In short, the purpose of source code is to <em>communicate</em> the workings of a piece of software to the next programmer who comes along. This could easily include your future self. </p> <p> Perhaps you disagree with that proposition. Perhaps you think that the purpose of source code is to produce working software. It's that, too, but that's not its only purpose. If that was the only purpose, you might as well write the software in machine code. </p> <p> Why do we have high-level programming languages like C#, Java, JavaScript, Ruby, Python, F#, Visual Basic, Haskell, heck - even C++? </p> <p> As far as I can tell, it's because programmers are all human, and humans have limited cognitive capacity. We can't keep track of hundreds, or thousands, of global variables, or the states of dozens of complex resources. We need tools that help us structure and understand complex systems so that they're broken down into (more) manageable chunks. High-level languages help us do that. </p> <p> The purpose of source code is to be understood. You read source code much more that you write. I'm not aware of any scientific studies, but I think most programmers will agree that over the lifetime of a code base, any line of code will be read orders of magnitude more often that it's edited. </p> <h3 id="b82afa298f114b8c89113ea5f40fc278"> Typing speed <a href="#b82afa298f114b8c89113ea5f40fc278" title="permalink">#</a> </h3> <p> How many lines of code do you produce during a productive working day? </p> <p> To be honest, I can't even answer that question myself. I've never measured it, since I consider it to be irrelevant. <a href="http://bit.ly/mythical-man-month">The Mythical Man-Month</a> gives the number as <em>10</em>, but let's be generous and pretend it's ten times that. This clearly depends on lots of factors, such as the language in which you're writing, the state of the code base, and so on. You'd tend to write more lines in a pristine greenfield code base, whereas you'll write fewer lines of code in a complicated legacy code base. </p> <p> How many characters is a line of code? Let's say it's 80 characters, because that's the maximum width code ought to have. I realise that many people write wider lines, but on the other hand, most developers (fortunately) use indentation, so as a counter-weight, code often has some blank space to the left as well. This is all back-of-the-envelope calculations anyway. </p> <p> When I worked in a Microsoft product group, we typically planned that a productive, 'full' day of coding was five hours. Even on productive days, the rest was used in meetings, administration, breaks, and so on. </p> <p> If you write code for five hours, and produce 100 lines of code, at 80 characters per line, that's 8,000 characters. Your IDE is likely to help you with statement completion and such, but for the sake of argument, let's pretend that you have to type it all in. </p> <p> 8,000 characters in five hours is 1,600 characters per hour, or 27 characters per minute. </p> <p> I'm not a particularly fast typist, but I can type ten times faster than that. </p> <p> Typing isn't a bottleneck. </p> <h3 id="cad0abab133848d98b4aada5e31d35d6"> Is more code worse? <a href="#cad0abab133848d98b4aada5e31d35d6" title="permalink">#</a> </h3> <p> I tend to <a href="http://blog.ploeh.dk/2013/02/04/BewareofProductivityTools">get drawn into these discussions from time to time</a>, but good programming has little to do with how fast you can produce lines of code. </p> <p> To be clear, I entirely accept that statement completion, refactoring support, and such are, in general, benign features. While I spend most of my programming time thinking and reading, I also tend to write code in bursts. The average count of lines per hour may not be great, but that's because averages smooth out the hills and the valleys of my activity. </p> <p> Still, increasingly frequent objection to some of my suggestions is that what I suggest implies 'too much' code. Recently, for example, I had to defend the merits of the <a href="https://martinfowler.com/bliki/FluentInterface.html">Fluent</a> Builder pattern that I suggest in my <a href="http://blog.ploeh.dk/2014/05/19/di-friendly-library">DI-Friendly Library</a> article. </p> <p> As another example, consider two alternatives for modelling a restaurant reservation. First, here's a terse option: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Reservation</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;Date&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;">string</span>&nbsp;Email&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;">string</span>&nbsp;Name&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;">int</span>&nbsp;Quantity&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;">bool</span>&nbsp;IsAccepted&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">set</span>;&nbsp;} }</pre> </p> <p> Here's a longer alternative: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Reservation</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Reservation( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;date, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;name, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;email, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;quantity)&nbsp;: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>(date,&nbsp;name,&nbsp;email,&nbsp;quantity,&nbsp;<span style="color:blue;">false</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;Reservation( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;date, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;name, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;email, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;quantity, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">bool</span>&nbsp;isAccepted) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date&nbsp;=&nbsp;date; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;name; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Email&nbsp;=&nbsp;email; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Quantity&nbsp;=&nbsp;quantity; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IsAccepted&nbsp;=&nbsp;isAccepted; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;Date&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">string</span>&nbsp;Name&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">string</span>&nbsp;Email&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">int</span>&nbsp;Quantity&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;IsAccepted&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Reservation</span>&nbsp;WithDate(<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;newDate) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Reservation</span>(newDate,&nbsp;Name,&nbsp;Email,&nbsp;Quantity,&nbsp;IsAccepted); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Reservation</span>&nbsp;WithName(<span style="color:blue;">string</span>&nbsp;newName) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Reservation</span>(Date,&nbsp;newName,&nbsp;Email,&nbsp;Quantity,&nbsp;IsAccepted); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Reservation</span>&nbsp;WithEmail(<span style="color:blue;">string</span>&nbsp;newEmail) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Reservation</span>(Date,&nbsp;Name,&nbsp;newEmail,&nbsp;Quantity,&nbsp;IsAccepted); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Reservation</span>&nbsp;WithQuantity(<span style="color:blue;">int</span>&nbsp;newQuantity) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Reservation</span>(Date,&nbsp;Name,&nbsp;Email,&nbsp;newQuantity,&nbsp;IsAccepted); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Reservation</span>&nbsp;Accept() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Reservation</span>(Date,&nbsp;Name,&nbsp;Email,&nbsp;Quantity,&nbsp;<span style="color:blue;">true</span>); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;Equals(<span style="color:blue;">object</span>&nbsp;obj) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!(obj&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:#2b91af;">Reservation</span>&nbsp;other)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;Equals(Date,&nbsp;other.Date) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;&amp;&nbsp;Equals(Name,&nbsp;other.Name) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;&amp;&nbsp;Equals(Email,&nbsp;other.Email) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;&amp;&nbsp;Equals(Quantity,&nbsp;other.Quantity) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;&amp;&nbsp;Equals(IsAccepted,&nbsp;other.IsAccepted); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">int</span>&nbsp;GetHashCode() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date.GetHashCode()&nbsp;^ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name.GetHashCode()&nbsp;^ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Email.GetHashCode()&nbsp;^ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Quantity.GetHashCode()&nbsp;^ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IsAccepted.GetHashCode(); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Which alternative is better? The short version is eight lines of code, including the curly brackets. The longer version is 78 lines of code. That's ten times as much. </p> <p> I prefer the longer version. While it takes longer to type, it comes with several benefits. The main benefit is that because it's immutable, it can have structural equality. This makes it trivial to compare objects, which, for example, is something you do all the time in unit test assertions. Another benefit is that such <a href="http://blog.ploeh.dk/2015/01/19/from-primitive-obsession-to-domain-modelling">Value Objects make better domain models</a>. The above <code>Reservation</code> <a href="https://martinfowler.com/bliki/ValueObject.html">Value Object</a> only shows the slightest sign of emerging domain logic in the <code>Accept</code> method, but once you start modelling like this, such objects seem to attract more domain behaviour. </p> <h3 id="78654bcab6ee4c57a24a5a41adf6c0fa"> Maintenance burden <a href="#78654bcab6ee4c57a24a5a41adf6c0fa" title="permalink">#</a> </h3> <p> Perhaps you're now convinced that typing speed may not be the bottleneck, but you still feel that you don't like the verbose <code>Reservation</code> alternative. More code could be an increased maintenance burden. </p> <p> Consider those <code>With[...]</code> methods, such as <code>WithName</code>, <code>WithQuantity</code>, and so on. Once you make objects immutable, such copy-and-update methods become indispensable. They enable you to change a single property of an object, while keeping all other values intact: </p> <p> <pre>&gt; <span style="color:blue;">var</span>&nbsp;r&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Reservation</span>(<span style="color:#2b91af;">DateTimeOffset</span>.Now,&nbsp;<span style="color:#a31515;">&quot;Foo&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;foo@example.com&quot;</span>,&nbsp;3); &gt; r.WithQuantity(4) Reservation { Date=[11.09.2018 19:19:29 +02:00], Email="foo@example.com", IsAccepted=false, Name="Foo", Quantity=4 }</pre> </p> <p> While convenient, such methods can increase the maintenance burden. If you realise that you need to change the name of one of the properties, you'll have to remember to also change the name of the copy-and-update method. For example, if you change <code>Quantity</code> to <code>NumberOfGuests</code>, you'll have to also remember to rename <code>WithQuantity</code> to <code>WithNumberOfGuests</code>. </p> <p> I'm not sure that I'm ready to concede that this is a prohibitive strain on the sustainability of a code base, but I do grant that it's a nuisance. This is one of the many reasons that I prefer to use programming languages better equipped for such domain modelling. In <a href="https://fsharp.org">F#</a>, for example, a record type similar to the above immutable <code>Reservation</code> class would be a one-liner: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;Reservation&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;Date&nbsp;:&nbsp;DateTimeOffset;&nbsp;Name&nbsp;:&nbsp;string;&nbsp;Email&nbsp;:&nbsp;string;&nbsp;Quantity&nbsp;:&nbsp;int;&nbsp;IsAccepted&nbsp;:&nbsp;bool&nbsp;}</pre> </p> <p> Such a declarative approach to types produces an immutable record with the same capabilities as the 78 lines of C# code. </p> <p> That's a different story, though. There's little correlation between the size of code, and how 'good' it is. Sometimes, less code is better; sometimes, more code is better. </p> <h3 id="ec55edfbe2a245b0b56188d4e8c6fbfb"> Summary <a href="#ec55edfbe2a245b0b56188d4e8c6fbfb" title="permalink">#</a> </h3> <p> I'll dispense with the usual Edsger Dijkstra and Bill Gates quotes on lines of code. The point that lines of code is a useless metric in software development has been made already. My point is a corollary. Apparently, it has to be explicitly stated: <em>Programmer productivity has nothing to do with typing speed.</em> </p> <p> Unless you're disabled in some way, you can type fast enough to be a productive programmer. Typing isn't a programming bottleneck. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="4bfb1d54e38449c7bc5d30e171d01179"> <div class="comment-author"><a href="http://honestillusion.com">James Curran</a></div> <div class="comment-content"> While I accept most of what you say, you are overlooking one key point: Better typists are better typists. Speed of typing (and volume of code produced) is the only statistic you look at. But what about <em>quality</em>? <br/> Watch a bad typist code. (It's easier with coding-heavy tutorial videos). It usually go as: type four or five characters, backspace, make a correction, type another six characters, backspace, make another fix, type a few more character, etc. <br/> They rarely get more than 10 keystrokes out before have to stop and go back. This reeks havoc with your cognitive flow, and makes it much harder to get into the "groove" of coding. Once you can type fluidly, you can concetrate on the code itself, rather than the mechanics of entering it. </div> <div class="comment-date">2018-09-19 02:02 UTC</div> </div> <div class="comment" id="3074a90b8bdb483dbc47d2364f056254"> <div class="comment-author"><a href="https://davideguida.com">Davide Guida</a></div> <div class="comment-content"> Lines of code has nothing to do with productivity. As professionals I think we all know this. <br /> Moreover, in many cases, too much verbosity might only lead to more defects (unless you're a strong advocate of TDD et similia)<br /> That said, one thing that I really liked about your article is the version of the Builder pattern you've implemented in the Reservation class. I love immutability in my classes and I often use the Builder pattern implemented as a inner class, just to be able to access the private cTor. <br/> One thing that I don't like with your approach is that in case you have a bit parameter list in your cTor (as you do in the example), the consumers are forced to create a "dummy" instance and then call the WithXXX() methods on it when possible. I guess it could be solved adding a static readonly Empty property on the Reservation class that can be used as a starting point. <br/> Anyways thank you for sharing this! </div> <div class="comment-date">2018-09-19 11:02 UTC</div> </div> <div class="comment" id="a4f8063cfaf84a10badd28981fac1ac5"> <div class="comment-author"><a href="http://blog.ploeh.dk">Mark Seemann</a></div> <div class="comment-content"> <p> James, thank you for writing. I agree that being able to type out your thoughts as fast as possible lowers the barrier between your brain and whatever medium you're working in. I had something similar in mind when I wrote <blockquote> "I also tend to write code in bursts. The average count of lines per hour may not be great, but that's because averages smooth out the hills and the valleys of my activity." </blockquote> I do, however, have mounting concerns about what you call the <em>groove</em> of coding. Flow state is generally characterised by a lack of reflection that I have often found to be counter-productive. These days, when programming, I deliberately use the Pomodoro technique - not to motivate me to code, but to force me to take breaks. Uncountable are the times I've had an important realisation about my work as soon as I'm away from the keyboard. These insights never seem to come to me when I'm in flow. </p> </div> <div class="comment-date">2018-09-21 4:53 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. The Lazy functor http://blog.ploeh.dk/2018/09/10/the-lazy-functor 2018-09-10T05:38:00+00:00 Mark Seemann <div id="post"> <p> <em>Lazy evaluation forms a functor. An article for object-oriented programmers.</em> </p> <p> This article is an instalment in <a href="http://blog.ploeh.dk/2018/03/22/functors">an article series about functors</a>. Previous articles have covered <a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">Maybe</a>, <a href="http://blog.ploeh.dk/2018/08/06/a-tree-functor">rose trees</a>, and other functors. This article provides another example. </p> <p> Most programming languages are eagerly evaluated. Sometimes, however, you'd like to defer execution of an expensive operation. On .NET, you can use <a href="https://docs.microsoft.com/en-us/dotnet/api/system.lazy-1">Lazy&lt;T&gt;</a> to achieve that goal. This generic type, like so many others, forms a functor. </p> <h3 id="0bf1fee5cdf14792a9d235630dd6fc4c"> Functor <a href="#0bf1fee5cdf14792a9d235630dd6fc4c" title="permalink">#</a> </h3> <p> You can implement an idiomatic <code>Select</code> extension method for <code>Lazy&lt;T&gt;</code> like this: </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;">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;">Lazy</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;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;(()&nbsp;=&gt;&nbsp;selector(source.Value)); }</pre> </p> <p> This would, for example, enable you to write code like this: </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;">string</span>&gt;&nbsp;y&nbsp;=&nbsp;x.Select(i&nbsp;=&gt;&nbsp;i.ToString());</pre> </p> <p> Or, using query syntax: </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;">string</span>&gt;&nbsp;y&nbsp;=&nbsp;<span style="color:blue;">from</span>&nbsp;i&nbsp;<span style="color:blue;">in</span>&nbsp;x&nbsp;<span style="color:blue;">select</span>&nbsp;i.ToString();</pre> </p> <p> You can add more steps to such a pipeline of lazy computation until you finally decide to force evaluation with the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.lazy-1.value">Value</a> property. </p> <p> Notice that while the <code>Select</code> method looks like it might force evaluation as well, by accessing the <code>Value</code> property, this happens inside a new lazily evaluated lambda expression. Thus, all steps in a <code>Lazy</code> pipeline are deferred until evaluation is forced. </p> <h3 id="35bdade6fc5d483da65d7d9623f23aa6"> First functor law <a href="#35bdade6fc5d483da65d7d9623f23aa6" title="permalink">#</a> </h3> <p> The <code>Select</code> method obeys the first functor law. As usual in this article series, actually proving that this is the case belongs in the realm of computer science. Instead of proving that the law holds, you can demonstrate that it does using property-based testing. The following example shows a single property written with <a href="https://fscheck.github.io/FsCheck/">FsCheck</a> 2.11.0 and <a href="https://xunit.github.io/">xUnit.net</a> 2.4.0. </p> <p> <pre>[<span style="color:#2b91af;">Property</span>(QuietOnSuccess&nbsp;=&nbsp;<span style="color:blue;">true</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;LazyObeysFirstFunctorLaw(<span style="color:blue;">int</span>&nbsp;i) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;left&nbsp;=&nbsp;<span style="color:#2b91af;">Lazy</span>.FromValue(i); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;right&nbsp;=&nbsp;<span style="color:#2b91af;">Lazy</span>.FromValue(i).Select(x&nbsp;=&gt;&nbsp;x); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(left.Value,&nbsp;right.Value); }</pre> </p> <p> Even though you may feel that a property-based test gives you more confidence than a few hard-coded examples, such a test is nothing but a demonstration of the first functor law. It's no proof, and it only demonstrates that the law holds for <code>Lazy&lt;int&gt;</code>, not that it holds for <code>Lazy&lt;string&gt;</code>, <code>Lazy&lt;Address&gt;</code>, etcetera. </p> <p> Both this property and the next uses this little static helper 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;">T</span>&gt;&nbsp;FromValue&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">T</span>&nbsp;value) { &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;">T</span>&gt;(()&nbsp;=&gt;&nbsp;value); }</pre> </p> <p> This helper method is only a convenience. You can put in a delay if you want to pretend that actual lazy evaluation takes place. It'll make the tests run slower, but otherwise will not affect the outcome. </p> <h3 id="dcbd7ed68831441d85960a148336d82c"> Second functor law <a href="#dcbd7ed68831441d85960a148336d82c" title="permalink">#</a> </h3> <p> As is the case with the first functor law, you can also use a property to demonstrate that the second functor law holds: </p> <p> <pre>[<span style="color:#2b91af;">Property</span>(QuietOnSuccess&nbsp;=&nbsp;<span style="color:blue;">true</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;LazyObeysSecondFunctorLaw( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">byte</span>&gt;&nbsp;f, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;g, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;i) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;left&nbsp;=&nbsp;<span style="color:#2b91af;">Lazy</span>.FromValue(i).Select(g).Select(f); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;right&nbsp;=&nbsp;<span style="color:#2b91af;">Lazy</span>.FromValue(i).Select(x&nbsp;=&gt;&nbsp;f(g(x))); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(left.Value,&nbsp;right.Value); }</pre> </p> <p> Again the same admonitions apply: that property is no proof. It does show, however, that given two functions, <code>f</code> and <code>g</code>, it doesn't matter if you map a <code>Lazy</code> computation in one or two steps. The output is the same in both cases. </p> <h3 id="b7c5e06037a64c07822997dc1ede3921"> F# <a href="#b7c5e06037a64c07822997dc1ede3921" title="permalink">#</a> </h3> <p> <a href="https://fsharp.org">F#</a> has <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/lazy-computations">built-in language support for lazy evaluations</a>, but surprisingly doesn't supply a <code>map</code> function. You can, however, easily implement such a function yourself: </p> <p> <pre><span style="color:blue;">module</span>&nbsp;Lazy&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;(&#39;a&nbsp;-&gt;&nbsp;&#39;b)&nbsp;-&gt;&nbsp;Lazy&lt;&#39;a&gt;&nbsp;-&gt;&nbsp;Lazy&lt;&#39;b&gt;</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;map&nbsp;f&nbsp;(x&nbsp;:&nbsp;Lazy&lt;&#39;a&gt;)&nbsp;=&nbsp;<span style="color:blue;">lazy</span>&nbsp;f&nbsp;x.Value</pre> </p> <p> This enables you to write code like this: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;(x&nbsp;:&nbsp;Lazy&lt;int&gt;)&nbsp;=&nbsp;//&nbsp;...</span> <span style="color:blue;">let</span>&nbsp;(y&nbsp;:&nbsp;Lazy&lt;string&gt;)&nbsp;=&nbsp;x&nbsp;|&gt;&nbsp;Lazy.map&nbsp;string</pre> </p> <p> The F# language feature is based on the same <code>Lazy&lt;T&gt;</code> class that you can use from C# (and Visual Basic .NET), so the behaviour is the same as described above. The functor laws hold for the <code>Lazy.map</code> function just like it holds for the above <code>Select</code> method. </p> <h3 id="545d7a227c154f2d89dd3b0abbc0d49d"> Haskell <a href="#545d7a227c154f2d89dd3b0abbc0d49d" title="permalink">#</a> </h3> <p> Unlinke C#, F#, and most other programming languages, <a href="https://www.haskell.org">Haskell</a> is lazily evaluated. All values, whether scalar or complex, are lazy by default. For that reason, there's no explicit <em>Lazy</em> type in Haskell. </p> <p> Haskell values are, in themselves, not functors, but you can put any value into the <a href="http://blog.ploeh.dk/2018/09/03/the-identity-functor">Identity functor</a>. Since all values are already lazy, you could view <code>Identity</code> as Haskell's <em>Lazy</em> functor. </p> <p> The equivalence is only partial, however. .NET <code>Lazy</code> objects are small state machines. Before you've forced evaluation, they carry around the expression to be evaluated. Once you've evaluated the value once, <code>Lazy</code> objects effectively replace the lazy expression with its result. Thus, the next time you access the <code>Value</code> property, you immediately receive the result. </p> <p> Haskell's lazily evaluated values are different. Since they're immutable, they don't 'change state' like that. On the other hand, sometimes the Haskell compiler can identify optimisations that it can apply to make lazily evaluated values more efficient. In other cases, you may have to apply more explicit memoisation. </p> <h3 id="6adbe0c495f14e1eaac983c80df10ac4"> Summary <a href="#6adbe0c495f14e1eaac983c80df10ac4" title="permalink">#</a> </h3> <p> In languages with eager evaluation (which is most of them), you can model deferred executation as a functor. This enables you to compose lazily evaluated expressions piecemeal. </p> <p> <strong>Next:</strong> Asynchronous functors. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. The Identity functor http://blog.ploeh.dk/2018/09/03/the-identity-functor 2018-09-03T06:46:00+00:00 Mark Seemann <div id="post"> <p> <em>The Identity functor is a data container that doesn't do anything. It's a functor nonetheless. An article for object-oriented programmers.</em> </p> <p> This article is an instalment in <a href="http://blog.ploeh.dk/2018/03/22/functors">an article series about functors</a>. In previous articles, you've learned about useful functors such as <a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">Maybe</a>. In this article, you'll learn about a (practically) useless functor called <em>Identity</em>. You can skip this article if you want. </p> <p> If Identity is useless, then why bother? </p> <p> The inutility of Identity doesn't mean that it doesn't exist. The Identity functor exists, whether it's useful or not. You can ignore it, but it still exists. In C# or <a href="https://fsharp.org">F#</a> I've never had any use for it (although I've <a href="http://blog.ploeh.dk/2017/09/04/builder-as-identity">described it before</a>), while it turns out to be occasionally useful in <a href="https://www.haskell.org">Haskell</a>, where it's built-in. The value of Identity is language-dependent. </p> <p> You may still derive value from this article. My motivation for writing it is to add another example to the set of functor examples presented in this article series. By presenting a varied selection of functors, it's my hope that you, from examples, gain insight. </p> <h3 id="b0e1913a128445719058616dfdf0f66b"> Identity objects <a href="#b0e1913a128445719058616dfdf0f66b" title="permalink">#</a> </h3> <p> You can implement Identity as a C# class: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Identity</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Identity(<span style="color:#2b91af;">T</span>&nbsp;item) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Item&nbsp;=&nbsp;item; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Item&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Identity</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;Select&lt;<span style="color:#2b91af;">TResult</span>&gt;(<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;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Identity</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;(selector(Item)); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;Equals(<span style="color:blue;">object</span>&nbsp;obj) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!(obj&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:#2b91af;">Identity</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;other)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;Equals(Item,&nbsp;other.Item); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">int</span>&nbsp;GetHashCode() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;Item?.GetHashCode()&nbsp;??&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> This class is just a wrapper around any object of the generic type <code>T</code>. The value could even be <code>null</code> if <code>T</code> is a reference type. </p> <p> Since <code>Identity&lt;T&gt;</code> exposes the <code>Select</code> instance method, you can translate wrapped values, as this <em>C# Interactive</em> example demonstrates: </p> <p> <pre>&gt; <span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Identity</span>&lt;<span style="color:blue;">string</span>&gt;(<span style="color:#a31515;">&quot;foo&quot;</span>).Select(s&nbsp;=&gt;&nbsp;s.Length) Identity&lt;int&gt; { Item=3 }</pre> </p> <p> You can also, if you prefer, use query syntax: </p> <p> <pre>&gt; <span style="color:blue;">from</span>&nbsp;i&nbsp;<span style="color:blue;">in</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Identity</span>&lt;<span style="color:blue;">int</span>&gt;(2)&nbsp;<span style="color:blue;">select</span>&nbsp;<span style="color:#a31515;">&#39;f&#39;</span>&nbsp;+&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">String</span>(<span style="color:#a31515;">&#39;o&#39;</span>,&nbsp;i) Identity&lt;string&gt; { Item="foo" }</pre> </p> <p> You can also unwrap the value: </p> <p> <pre>&gt; <span style="color:#2b91af;">Identity</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;x&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Identity</span>&lt;<span style="color:blue;">string</span>&gt;(<span style="color:#a31515;">&quot;bar&quot;</span>); &gt; x.Item "bar"</pre> </p> <p> Admittedly, this isn't the most exciting or useful class you could ever write. It is, however, a functor. </p> <h3 id="3cc3d00bdcbc4ad48008dac89fe748eb"> First functor law <a href="#3cc3d00bdcbc4ad48008dac89fe748eb" title="permalink">#</a> </h3> <p> The <code>Select</code> method obeys the first functor law. As usual in this article series, actually proving that this is the case belongs in the realm of computer science. I would guess, however, that in this particular case, the proof would be manageable. Instead of proving this, though, you can demonstrate that the law holds using property-based testing. The following example shows a single property written with <a href="https://fscheck.github.io/FsCheck/">FsCheck</a> 2.11.0 and <a href="https://xunit.github.io/">xUnit.net</a> 2.4.0. </p> <p> <pre>[<span style="color:#2b91af;">Property</span>(QuietOnSuccess&nbsp;=&nbsp;<span style="color:blue;">true</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;IdentityObeysFirstFunctorLaw(<span style="color:blue;">int</span>&nbsp;i) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;left&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Identity</span>&lt;<span style="color:blue;">int</span>&gt;(i); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;right&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Identity</span>&lt;<span style="color:blue;">int</span>&gt;(i).Select(x&nbsp;=&gt;&nbsp;x); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(left,&nbsp;right); }</pre> </p> <p> Even though you may feel that a property-based test gives you more confidence than a few hard-coded examples, such a test is nothing but a demonstration of the first functor law. It's no proof, and it only demonstrates that the law holds for <code>Identity&lt;int&gt;</code>, not that it holds for <code>Identity&lt;string&gt;</code>, <code>Identity&lt;Customer&gt;</code>, etcetera. </p> <h3 id="eaa5115fe3a9432d994ddc3580c7f06d"> Second functor law <a href="#eaa5115fe3a9432d994ddc3580c7f06d" title="permalink">#</a> </h3> <p> As is the case with the first functor law, you can also use a property to demonstrate that the second functor law holds: </p> <p> <pre>[<span style="color:#2b91af;">Property</span>(QuietOnSuccess&nbsp;=&nbsp;<span style="color:blue;">true</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;IdentityObeysSecondFunctorLaw( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">byte</span>&gt;&nbsp;f, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;g, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;i) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;left&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Identity</span>&lt;<span style="color:blue;">int</span>&gt;(i).Select(g).Select(f); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;right&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Identity</span>&lt;<span style="color:blue;">int</span>&gt;(i).Select(x&nbsp;=&gt;&nbsp;f(g(x))); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(left,&nbsp;right); }</pre> </p> <p> Again the same admonitions apply: that property is no proof. It does show, however, that given two functions, <code>f</code> and <code>g</code>, it doesn't matter if you map an <code>Identity</code> object in one or two steps. The output is the same in both cases. </p> <h3 id="adb0f7a1e73042e8b570545de440fb52"> F# <a href="#adb0f7a1e73042e8b570545de440fb52" title="permalink">#</a> </h3> <p> While the <code>Identity</code> functor is built into the Haskell standard library, there's no Identity functor in F#. While it can be occasionally useful in Haskell, Identity is useless in F#, like it is in C#. Again, that doesn't imply that you can't define it. You can: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;Identity&lt;&#39;a&gt;&nbsp;=&nbsp;Identity&nbsp;<span style="color:blue;">of</span>&nbsp;&#39;a <span style="color:blue;">module</span>&nbsp;Identity&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;Identity&lt;&#39;a&gt;&nbsp;-&gt;&nbsp;&#39;a</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;get&nbsp;(Identity&nbsp;x)&nbsp;=&nbsp;x &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;(&#39;a&nbsp;-&gt;&nbsp;&#39;b)&nbsp;-&gt;&nbsp;Identity&lt;&#39;a&gt;&nbsp;-&gt;&nbsp;Identity&lt;&#39;b&gt;</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;map&nbsp;f&nbsp;(Identity&nbsp;x)&nbsp;=&nbsp;Identity&nbsp;(f&nbsp;x)</pre> </p> <p> With this type, you can wrap, map, and unwrap values to your heart's content: </p> <p> <pre>&gt; Identity "foo" |&gt; Identity.map Seq.length;; val it : Identity&lt;int&gt; = Identity 3 &gt; Identity 2 |&gt; Identity.map (fun i -&gt; "f" + String ('o', i));; val it : Identity&gt;string&gt; = Identity "foo" &gt; let x = Identity "bar";; val x : Identity&lt;string&gt; = Identity "bar" &gt; Identity.get x;; val it : string = "bar"</pre> </p> <p> There's not much point to this, apart from demonstrating that it's possible. </p> <h3 id="3ce0bfe49361464ba4bf143aee3c70e2"> Summary <a href="#3ce0bfe49361464ba4bf143aee3c70e2" title="permalink">#</a> </h3> <p> The Identity functor exists, and you can implement it in C# and F#, although I don't see any use for it. Haskell has a type system that can express abstractions such as <code>Functor</code> in the type system itself. In that language, then, you can define functions that return any type of functor (e.g. <code>Maybe</code>, <code>Tree</code>, and so on). If you need a plain vanilla version of such a function, you can make it return <code>Identity</code>. </p> <p> The point of this article was only to identify the existence of the Identity functor, and to perhaps illustrate that the concept of a functor encompasses various data structures and behaviours. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/09/10/the-lazy-functor">The Lazy functor</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. On Constructor Over-injection http://blog.ploeh.dk/2018/08/27/on-constructor-over-injection 2018-08-27T07:11:00+00:00 Mark Seemann <div id="post"> <p> <em>Constructor Over-injection is a code smell, not an anti-pattern.</em> </p> <p> Sometimes, people struggle with how to deal with the Constructor Over-injection code smell. Often, you can address it by <a href="http://blog.ploeh.dk/2010/02/02/RefactoringtoAggregateServices">refactoring to Facade Services</a>. This is possible when constructor arguments fall in two or more natural clusters. Sometimes, however, that isn't possible. </p> <h3 id="6ef3c9728f4f46e5a0a6c694b115705a"> Cross-cutting concerns <a href="#6ef3c9728f4f46e5a0a6c694b115705a" title="permalink">#</a> </h3> <p> Before we get to the heart of this post, I want to get something out of the way. Sometimes constructors have too many arguments because they request various services that represent cross-cutting concerns: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;Foo( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IBar</span>&nbsp;bar, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IBaz</span>&nbsp;baz, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IQux</span>&nbsp;qux, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IAuthorizationManager</span>&nbsp;authorizationManager, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">ILog</span>&nbsp;log, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">ICache</span>&nbsp;cache, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">ICircuitBreaker</span>&nbsp;breaker)</pre> </p> <p> This <code>Foo</code> class has seven dependencies passed via the constructor. Three of those (<code>bar</code>, <code>baz</code>, and <code>qux</code>) are regular dependencies. The other four are various incarnations of cross-cutting concerns: logging, caching, authorization, stability. As I describe in <a href="http://amzn.to/12p90MG">my book</a>, cross-cutting concerns are better addressed with <a href="https://en.wikipedia.org/wiki/Decorator_pattern">Decorators</a> or the <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">Chain of Responsibility</a> pattern. Thus, such a <code>Foo</code> constructor ought really to take just three arguments: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;Foo( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IBar</span>&nbsp;bar, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IBaz</span>&nbsp;baz, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IQux</span>&nbsp;qux)</pre> </p> <p> Making cross-cutting concerns 'disappear' like that could decrease the number of constructor arguments to an acceptable level, thereby effectively dealing with the Constructor Over-injection smell. Sometimes, however, that's not the issue. </p> <h3 id="00cc1f6794244596ac665cbc9e0919da"> No natural clusters <a href="#00cc1f6794244596ac665cbc9e0919da" title="permalink">#</a> </h3> <p> Occasionally, a class has many dependencies, and the dependencies form no natural clusters: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;Ploeh( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IBar</span>&nbsp;bar, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IBaz</span>&nbsp;baz, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IQux</span>&nbsp;qux, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IQuux</span>&nbsp;quux, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IQuuz</span>&nbsp;quuz, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">ICorge</span>&nbsp;corge, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IGrault</span>&nbsp;grault, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IGarply</span>&nbsp;garply, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IWaldo</span>&nbsp;waldo, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IFred</span>&nbsp;fred, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IPlugh</span>&nbsp;plugh, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IXyzzy</span>&nbsp;xyzzy, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IThud</span>&nbsp;thud) { &nbsp;&nbsp;&nbsp;&nbsp;Bar&nbsp;=&nbsp;bar; &nbsp;&nbsp;&nbsp;&nbsp;Baz&nbsp;=&nbsp;baz; &nbsp;&nbsp;&nbsp;&nbsp;Qux&nbsp;=&nbsp;qux; &nbsp;&nbsp;&nbsp;&nbsp;Quux&nbsp;=&nbsp;quux; &nbsp;&nbsp;&nbsp;&nbsp;Quuz&nbsp;=&nbsp;quuz; &nbsp;&nbsp;&nbsp;&nbsp;Corge&nbsp;=&nbsp;corge; &nbsp;&nbsp;&nbsp;&nbsp;Grault&nbsp;=&nbsp;grault; &nbsp;&nbsp;&nbsp;&nbsp;Garply&nbsp;=&nbsp;garply; &nbsp;&nbsp;&nbsp;&nbsp;Waldo&nbsp;=&nbsp;waldo; &nbsp;&nbsp;&nbsp;&nbsp;Fred&nbsp;=&nbsp;fred; &nbsp;&nbsp;&nbsp;&nbsp;Plugh&nbsp;=&nbsp;plugh; &nbsp;&nbsp;&nbsp;&nbsp;Xyzzy&nbsp;=&nbsp;xyzzy; &nbsp;&nbsp;&nbsp;&nbsp;Thud&nbsp;=&nbsp;thud; }</pre> </p> <p> This seems to be an obvious case of the Constructor Over-injection code smell. If you can't refactor to Facade Services, then what other options do you have? </p> <h3 id="486abcae3b934d958f8c3f0575e58db5"> Introducing a Parameter Object isn't likely to help <a href="#486abcae3b934d958f8c3f0575e58db5" title="permalink">#</a> </h3> <p> Some people, when they run into this type of situation, attempt to resolve it by <a href="https://refactoring.com/catalog/introduceParameterObject.html">introducing a Parameter Object</a>. In its simplest form, the Parameter Object is just a collection of properties that client code can access. In other cases, the Parameter Object is a <a href="https://en.wikipedia.org/wiki/Facade_pattern">Facade</a> over a DI Container. Sometimes, the Parameter Object is defined as an interface with read-only properties. </p> <p> One way to use such a Parameter Object could be like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;Ploeh(<span style="color:#2b91af;">DependencyCatalog</span>&nbsp;catalog) { &nbsp;&nbsp;&nbsp;&nbsp;Bar&nbsp;=&nbsp;catalog.Bar; &nbsp;&nbsp;&nbsp;&nbsp;Baz&nbsp;=&nbsp;catalog.Baz; &nbsp;&nbsp;&nbsp;&nbsp;Qux&nbsp;=&nbsp;catalog.Qux; &nbsp;&nbsp;&nbsp;&nbsp;Quux&nbsp;=&nbsp;catalog.Quux; &nbsp;&nbsp;&nbsp;&nbsp;Quuz&nbsp;=&nbsp;catalog.Quuz; &nbsp;&nbsp;&nbsp;&nbsp;Corge&nbsp;=&nbsp;catalog.Corge; &nbsp;&nbsp;&nbsp;&nbsp;Grault&nbsp;=&nbsp;catalog.Grault; &nbsp;&nbsp;&nbsp;&nbsp;Garply&nbsp;=&nbsp;catalog.Garply; &nbsp;&nbsp;&nbsp;&nbsp;Waldo&nbsp;=&nbsp;catalog.Waldo; &nbsp;&nbsp;&nbsp;&nbsp;Fred&nbsp;=&nbsp;catalog.Fred; &nbsp;&nbsp;&nbsp;&nbsp;Plugh&nbsp;=&nbsp;catalog.Plugh; &nbsp;&nbsp;&nbsp;&nbsp;Xyzzy&nbsp;=&nbsp;catalog.Xyzzy; &nbsp;&nbsp;&nbsp;&nbsp;Thud&nbsp;=&nbsp;catalog.Thud; }</pre> </p> <p> Alternatively, some people just store a reference to the Parameter Object and then access the read-only properties on an as-needed basis. </p> <p> None of those alternatives are likely to help. One problem is that such a <code>DependencyCatalog</code> will be likely to violate the <a href="https://en.wikipedia.org/wiki/Interface_segregation_principle">Interface Segregation Principle</a>, unless you take great care to make a 'dependency catalogue' per class. For instance, you'd be tempted to add <code>Wibble</code>, <code>Wobble</code>, and <code>Wubble</code> properties to the above <code>DependencyCatalog</code> class, because some other <code>Fnaah</code> class needs those dependencies in addition to <code>Bar</code>, <code>Fred</code>, and <code>Waldo</code>. </p> <h3 id="b6d3204fb4ad4e72a835b28f9aa2305b"> Deodorant <a href="#b6d3204fb4ad4e72a835b28f9aa2305b" title="permalink">#</a> </h3> <p> Fundamentally, Constructor Over-injection is a code smell. This means that it's an indication that something is not right; that there's an area of code that bears investigation. Code smells aren't problems in themselves, but rather symptoms. </p> <p> Constructor Over-injection tends to be a symptom that a class is doing too much: that it's violating the <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle</a>. Reducing thirteen constructor arguments to a single Parameter Object doesn't address the underlying problem. It only applies deodorant to the smell. </p> <p> Address, if you can, the underlying problem, and the symptom is likely to disappear as well. </p> <h3 id="ac21c35680d34943a1827d94e2e18533"> Guidance, not law <a href="#ac21c35680d34943a1827d94e2e18533" title="permalink">#</a> </h3> <p> This is only guidance. There could be cases where it's genuinely valid to have dozens of dependencies. I'm being deliberately vague, because I don't wish to go into an elaborate example. Usually, there's more than one way to solve a particular problem, and occasionally, it's possible that collecting many services in a single class would be appropriate. (This sounds like a case for the <a href="https://en.wikipedia.org/wiki/Composite_pattern">Composite</a> design pattern, but let's assume that there could be cases where that's not possible.) </p> <p> This is similar to using <a href="https://en.wikipedia.org/wiki/Cyclomatic_complexity">cyclomatic complexity</a> as a guide. Every now and then, a big, flat switch statement is just the best and most maintainable solution to a problem, even when it has a cyclomatic complexity of 37... </p> <p> Likewise, there could be cases where it's genuinely not a problem with dozens of constructor arguments. </p> <h3 id="7032a437458e45e58abd262b882b1442"> Summary <a href="#7032a437458e45e58abd262b882b1442" title="permalink">#</a> </h3> <p> Constructor Over-injection is a code smell, not an anti-pattern. It's a good idea to be aware of the smell, and address it when you discover it. You should, however, deal with the problem instead of applying deodorant to the smell. The underlying problem is usually that the class with the many dependencies has too many responsibilities. Address that problem, and the smell is likely to evaporate as well. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Reactive functor http://blog.ploeh.dk/2018/08/20/reactive-functor 2018-08-20T05:58:00+00:00 Mark Seemann <div id="post"> <p> <em>IObservable&lt;T&gt; is (also) a functor.</em> </p> <p> This article is an instalment in <a href="http://blog.ploeh.dk/2018/03/22/functors">an article series about functors</a>. While the previous articles showed, in great detail, how to turn various classes into functors, this article mostly serves as a place-holder. The purpose is only to point out that you don't have to create all functors yourself. Sometimes, they come as part of a reusable library. </p> <p> <a href="http://reactivex.io">Rx</a> is such a library, and <code>IObservable&lt;T&gt;</code> is a functor. (It's also a monad, but this is not a monad tutorial; it's a functor tutorial.) Reactive Extensions define a <code>Select</code> method for <code>IObservable&lt;T&gt;</code>, so if <code>source</code> is an <code>IObservable&lt;int&gt;</code>, you can translate it to <code>IObservable&lt;string&gt;</code> like this: </p> <p> <pre><span style="color:#2b91af;">IObservable</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;dest&nbsp;=&nbsp;source.Select(i&nbsp;=&gt;&nbsp;i.ToString()); </pre> </p> <p> Since the <code>Select</code> method is, indeed, called <code>Select</code> and has the signature </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IObservable</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;Select&lt;<span style="color:#2b91af;">TSource</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IObservable</span>&lt;<span style="color:#2b91af;">TSource</span>&gt;&nbsp;source, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">TSource</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;selector) </pre> </p> <p> you can also use C#'s query syntax: </p> <p> <pre><span style="color:#2b91af;">IObservable</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;dest&nbsp;=&nbsp;<span style="color:blue;">from</span>&nbsp;i&nbsp;<span style="color:blue;">in</span>&nbsp;source &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;i.ToString();</pre> </p> <p> In both of the above examples, I've explicitly declared the type of <code>dest</code> instead of using the <code>var</code> keyword. There's no practical reason to do this; I only did it to make the type clear to you. </p> <h3 id="3870ba1938904931acd9d36ce3a8ac53"> First functor law <a href="#3870ba1938904931acd9d36ce3a8ac53" title="permalink">#</a> </h3> <p> The <code>Select</code> method obeys the first functor law. As usual, it's proper computer-science work to actually prove that, but you can write some tests to demonstrate the first functor law for the <code>IObservable&lt;T&gt;</code> interface. In this article, you'll see a few parametrised tests written with <a href="https://xunit.github.io">xUnit.net</a>. Here's one that demonstrates that the first functor law holds: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(-101)] [<span style="color:#2b91af;">InlineData</span>(-1)] [<span style="color:#2b91af;">InlineData</span>(0)] [<span style="color:#2b91af;">InlineData</span>(1)] [<span style="color:#2b91af;">InlineData</span>(42)] [<span style="color:#2b91af;">InlineData</span>(1337)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">async</span>&nbsp;<span style="color:#2b91af;">Task</span>&nbsp;ObservableObeysFirstFunctorLaw(<span style="color:blue;">int</span>&nbsp;value) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;sut&nbsp;=&nbsp;<span style="color:blue;">new</span>[]&nbsp;{&nbsp;value&nbsp;}.ToObservable(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IObservable</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;projected&nbsp;=&nbsp;sut.Select(x&nbsp;=&gt;&nbsp;x); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;<span style="color:blue;">await</span>&nbsp;projected.FirstAsync(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(value,&nbsp;actual); }</pre> </p> <p> Here, I chose to implement the identity function as an anonymous lambda expression. In contrast, in a <a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">previous article</a>, I explicitly declared a function variable and called it <code>id</code>. Those two ways to express the identity function are equivalent. </p> <p> As always, I'd like to emphasise that this test doesn't <em>prove</em> that <code>IObservable&lt;T&gt;</code> obeys the first functor law. It only demonstrates that the law holds for those six examples. </p> <h3 id="e38867cbb29e4fb8839a76091c7db532"> Second functor law <a href="#e38867cbb29e4fb8839a76091c7db532" title="permalink">#</a> </h3> <p> Like the above example, you can also write a parametrised test that demonstrates that <code>IObservable&lt;T&gt;</code> obeys the second functor law: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(-101)] [<span style="color:#2b91af;">InlineData</span>(-1)] [<span style="color:#2b91af;">InlineData</span>(0)] [<span style="color:#2b91af;">InlineData</span>(1)] [<span style="color:#2b91af;">InlineData</span>(42)] [<span style="color:#2b91af;">InlineData</span>(1337)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">async</span>&nbsp;<span style="color:#2b91af;">Task</span>&nbsp;ObservableObeysSecondFunctorLaw(<span style="color:blue;">int</span>&nbsp;value) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;g(<span style="color:blue;">int</span>&nbsp;i)&nbsp;=&gt;&nbsp;i.ToString(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;f(<span style="color:blue;">string</span>&nbsp;s)&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:blue;">string</span>(s.Reverse().ToArray()); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;sut&nbsp;=&nbsp;<span style="color:blue;">new</span>[]&nbsp;{&nbsp;value&nbsp;}.ToObservable(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IObservable</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;projected&nbsp;=&nbsp;sut.Select(i&nbsp;=&gt;&nbsp;f(g(i))); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;<span style="color:blue;">await</span>&nbsp;projected.FirstAsync(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;expected&nbsp;=&nbsp;<span style="color:blue;">await</span>&nbsp;sut.Select(g).Select(f).FirstAsync(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(expected,&nbsp;actual); }</pre> </p> <p> This test defines two local functions, <code>f</code> and <code>g</code>. Instead of explicitly declaring the functions as <code>Func</code> variables, this test uses a (relatively) new C# feature called <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions">local functions</a>. </p> <p> Again, while the test doesn't prove anything, it demonstrates that for the six test cases, it doesn't matter if you project the observable in one or two steps. </p> <h3 id="74dc9987d2ae40ca94c6cbd5112a3238"> Summary <a href="#74dc9987d2ae40ca94c6cbd5112a3238" title="permalink">#</a> </h3> <p> The point of this article is mostly that functors are commonplace. While you may discover them in your own code, they may also come in a reusable library. If you already know C# LINQ based off <code>IEnumerable&lt;T&gt;</code>, much of Rx will be easy for you to learn. After all, it's the same abstraction, and <em>familiar abstractions make code readable</em>. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/09/03/the-identity-functor">The Identity functor</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. A Visitor functor http://blog.ploeh.dk/2018/08/13/a-visitor-functor 2018-08-13T06:56:00+00:00 Mark Seemann <div id="post"> <p> <em>Some Visitors can be functors. Another functor example for object-oriented programmers.</em> </p> <p> This article is an instalment in <a href="http://blog.ploeh.dk/2018/03/22/functors">an article series about functors</a>. In the <a href="http://blog.ploeh.dk/2018/08/06/a-tree-functor">previous article</a>, you saw how to implement a generalised tree as a functor. In this article, you'll see another functor example, which will also be an application of the <a href="https://en.wikipedia.org/wiki/Visitor_pattern">Visitor design pattern</a>. </p> <p> The Visitor design pattern is often described in such a way that it's based on mutation; the <code>Visit</code> and <code>Accept</code> methods in those descriptions typically return <code>void</code>. You can, however, also implement immutable variations. This blog already contains <a href="http://blog.ploeh.dk/2011/05/16/TennisKatawithimmutabletypesandacyclomaticcomplexityof1">an older example of this</a>. </p> <h3 id="e58c06335ed34b45a31024e88464c23f"> Visitor <a href="#e58c06335ed34b45a31024e88464c23f" title="permalink">#</a> </h3> <p> In this article, you'll see how to implement a full binary tree using the Visitor design pattern. You can make the tree generic, so that each node can contain values of any generic type. </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Accept&lt;<span style="color:#2b91af;">TResult</span>&gt;(<span style="color:#2b91af;">IBinaryTreeVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;visitor); }</pre> </p> <p> As promised, this interface implies an immutable variant where the <code>Accept</code> method doesn't mutate the input Visitor, but rather returns a new value. You can learn how you arrive at this particular generic method signature in my article <a href="http://blog.ploeh.dk/2018/06/25/visitor-as-a-sum-type">Visitor as a sum type</a>. </p> <p> A full binary tree is a tree where each node has either zero or two children. This means that a Visitor must have two methods, one for each case: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IBinaryTreeVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Visit(<span style="color:#2b91af;">Node</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;node); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Visit(<span style="color:#2b91af;">Leaf</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;leaf); }</pre> </p> <p> The <code>IBinaryTreeVisitor&lt;T, TResult&gt;</code> interface introduces two new concrete classes: <code>Node&lt;T&gt;</code> and <code>Leaf&lt;T&gt;</code>. A leaf node is a node with zero children: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Leaf</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;:&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Item&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Leaf(<span style="color:#2b91af;">T</span>&nbsp;item) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(item&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(item)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Item&nbsp;=&nbsp;item; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Accept&lt;<span style="color:#2b91af;">TResult</span>&gt;(<span style="color:#2b91af;">IBinaryTreeVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;visitor) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(visitor&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(visitor)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;visitor.Visit(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;Equals(<span style="color:blue;">object</span>&nbsp;obj) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!(obj&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:#2b91af;">Leaf</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;other)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;Equals(Item,&nbsp;other.Item); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">int</span>&nbsp;GetHashCode() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;Item.GetHashCode(); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> While a leaf node has no children, it still contains an <code>Item</code> of the generic type <code>T</code>. A leaf node still counts as a binary tree, so it implements the <code>IBinaryTree&lt;T&gt;</code> interface. Complying with the Visitor design pattern, its <code>Accept</code> method is implemented using double dispatch. Thereby, any <code>visitor</code> knows that it's now visiting a concrete <code>Leaf&lt;T&gt;</code> object. </p> <p> Likewise, a node is a (sub)tree: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Node</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;:&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Item&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;Left&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;Right&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Node(<span style="color:#2b91af;">T</span>&nbsp;item,&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;left,&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;right) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(item&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(item)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(left&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(left)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(right&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(right)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Item&nbsp;=&nbsp;item; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Left&nbsp;=&nbsp;left; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Right&nbsp;=&nbsp;right; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Accept&lt;<span style="color:#2b91af;">TResult</span>&gt;(<span style="color:#2b91af;">IBinaryTreeVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;visitor) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(visitor&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(visitor)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;visitor.Visit(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;Equals(<span style="color:blue;">object</span>&nbsp;obj) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!(obj&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:#2b91af;">Node</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;other)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;Equals(Item,&nbsp;other.Item) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;&amp;&nbsp;Equals(Left,&nbsp;other.Left) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;&amp;&nbsp;Equals(Right,&nbsp;other.Right); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">int</span>&nbsp;GetHashCode() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;Item.GetHashCode()&nbsp;^&nbsp;Left.GetHashCode()&nbsp;^&nbsp;Right.GetHashCode(); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> In addition to an <code>Item</code>, a <code>Node&lt;T&gt;</code> object also contains a <code>Left</code> and a <code>Right</code> sub-tree. Notice that the <code>Accept</code> method is literally identical to <code>Leaf&lt;T&gt;.Accept</code>. Its behaviour differs, though, because <code>this</code> has a different type. </p> <p> A couple of static helper methods makes it a bit easier to create binary tree objects: </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;">BinaryTree</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;Leaf&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">T</span>&nbsp;item) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Leaf</span>&lt;<span style="color:#2b91af;">T</span>&gt;(item); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;Create&lt;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">T</span>&nbsp;item, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;left, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;right) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Node</span>&lt;<span style="color:#2b91af;">T</span>&gt;(item,&nbsp;left,&nbsp;right); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> The main convenience of these two methods is that C# (limited) type inference enables you to create tree objects without explicitly typing out the generic type argument every time. You'll soon see an example of creating a binary tree of integers. </p> <h3 id="75e8ba18e47049a6809896e0189fe0d9"> Functor <a href="#75e8ba18e47049a6809896e0189fe0d9" title="permalink">#</a> </h3> <p> Since <code>IBinaryTree&lt;T&gt;</code> is a generic type, you should consider whether it's a functor. Given the overall topic of this article, you'd hardly be surprised that it is. </p> <p> In the previous two functor examples (<a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">Maybe</a> and <a href="http://blog.ploeh.dk/2018/08/06/a-tree-functor">Tree</a>), the <code>Select</code> methods were instance methods. On the other hand, the .NET Base Class Library implements <code>IEnumerable&lt;T&gt;.Select</code> as an extension method. You can do the same with this binary tree Visitor: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;Select&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;">IBinaryTree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;tree, &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;">if</span>&nbsp;(tree&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(tree)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(selector&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(selector)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;visitor&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SelectBinaryTreeVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;(selector); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;tree.Accept(visitor); }</pre> </p> <p> This <code>Select</code> method has the right signature for turning <code>IBinaryTree&lt;T&gt;</code> into a functor. It starts by creating a new instance of a private helper class called <code>SelectBinaryTreeVisitor&lt;T, TResult&gt;</code>. Notice that this class has two generic type arguments: the source type <code>T</code> and the destination type <code>TResult</code>. It also contains <code>selector</code>, so that it knows what to do with each <code>Item</code> it encounters. </p> <p> <code>SelectBinaryTreeVisitor&lt;T, TResult&gt;</code> is a Visitor, so you pass it to the <code>tree</code> object's <code>Accept</code> method. The <code>Accept</code> method returns a variable that you can directly return, because, as you'll see below, the return type of <code>SelectBinaryTreeVisitor&lt;T, TResult&gt;</code>'s <code>Visit</code> methods is <code>IBinaryTree&lt;TResult&gt;</code>. </p> <p> <code>SelectBinaryTreeVisitor&lt;T, TResult&gt;</code> is a <code>private</code> helper class, and is the most complex functor implementation you've seen so far. The Visitor design pattern solves a specific problem, but it was never the simplest of design patterns. </p> <p> <pre><span style="color:blue;">private</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">SelectBinaryTreeVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;: &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IBinaryTreeVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">TResult</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;">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;">public</span>&nbsp;SelectBinaryTreeVisitor(<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;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(selector&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(selector)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.selector&nbsp;=&nbsp;selector; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;Visit(<span style="color:#2b91af;">Leaf</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;leaf) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;mappedItem&nbsp;=&nbsp;selector(leaf.Item); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;Leaf(mappedItem); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;Visit(<span style="color:#2b91af;">Node</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;node) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;mappedItem&nbsp;=&nbsp;selector(node.Item); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;mappedLeft&nbsp;=&nbsp;node.Left.Accept(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;mappedRight&nbsp;=&nbsp;node.Right.Accept(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;Create(mappedItem,&nbsp;mappedLeft,&nbsp;mappedRight); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Since the class implements <code>IBinaryTreeVisitor&lt;T,&nbsp;IBinaryTree&lt;TResult&gt;&gt;</code>, it must implement the two <code>Visit</code> overloads. The overload for <code>Leaf&lt;T&gt;</code> is simple: use the <code>selector</code> to map the <code>Item</code>, and use the <code>Leaf</code> convenience method to return a new <code>Leaf&lt;TResult&gt;</code> containing the mapped item. Notice that while <code>SelectBinaryTreeVisitor&lt;T, TResult&gt;</code> looks like it has a generic 'return' type argument of <code>TResult</code>, it implements <code>IBinaryTreeVisitor&lt;T,&nbsp;IBinaryTree&lt;TResult&gt;&gt;</code>, which means that the return type of each <code>Visit</code> method must be <code>IBinaryTree&lt;TResult&gt;</code>, and that matches <code>Leaf&lt;TResult&gt;</code>. </p> <p> The overload for a <code>Node&lt;T&gt;</code> object looks twice as big, but it's still simple. Like the leaf overload, it uses <code>selector</code> to map the <code>Item</code>, but in addition to that, it must also recursively map the <code>Left</code> and <code>Right</code> sub-trees. It does this by passing itself, in its role as a Visitor, to the left and right nodes' <code>Accept</code> methods. This returns mapped sub-trees that can be used to create a new mapped tree, using the <code>Create</code> convenience method. </p> <h3 id="05044a8452844974980483246078f0e2"> Usage <a href="#05044a8452844974980483246078f0e2" title="permalink">#</a> </h3> <p> While the implementation of such a Visitor is cumbersome, it's easy enough to use. </p> <p> <pre><span style="color:blue;">var</span>&nbsp;source&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Create(42, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Create(1337, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(0), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(-22)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(100));</pre> </p> <p> You can translate this binary tree of integers to a tree of strings using method call syntax: </p> <p> <pre><span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;dest&nbsp;=&nbsp;source.Select(i&nbsp;=&gt;&nbsp;i.ToString()); </pre> </p> <p> or by using query syntax: </p> <p> <pre><span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;dest&nbsp;=&nbsp;<span style="color:blue;">from</span>&nbsp;i&nbsp;<span style="color:blue;">in</span>&nbsp;source &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;i.ToString();</pre> </p> <p> In both of these examples, I've explicitly declared the type of <code>dest</code> instead of using the <code>var</code> keyword. There's no practical reason to do this; I only did it to make the type clear to you. </p> <h3 id="6db319918e384c2e82c64aba8e24d73c"> Haskell <a href="#6db319918e384c2e82c64aba8e24d73c" title="permalink">#</a> </h3> <p> Why would anyone ever do something so complicated as this? </p> <p> The answer to such a question is, I believe, that it's only complicated in <em>some</em> programming languages. In <a href="https://haskell.org">Haskell</a>, <em>all</em> of the above can be reduce to <em>a single</em> type declaration: </p> <p> <pre><span style="color:blue;">data</span>&nbsp;<span style="color:#dd0000;">BinaryTree</span>&nbsp;a&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">Node</span>&nbsp;a&nbsp;(<span style="color:#dd0000;">BinaryTree</span>&nbsp;a)&nbsp;(<span style="color:#dd0000;">BinaryTree</span>&nbsp;a)&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Leaf</span>&nbsp;a &nbsp;&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#a31515;">Show</span>,&nbsp;<span style="color:#a31515;">Eq</span>,&nbsp;<span style="color:#a31515;">Functor</span>)</pre> </p> <p> Notice that the Haskell compiler can automatically derive an implementation of the <code>Functor</code> typeclass, although that does require the <code>DeriveFunctor</code> language extension. </p> <p> This may explain why binary trees aren't part of object-oriented programmers' normal tool box, whereas they are more commonplace in functional programming. </p> <p> While not strictly required, in order to keep the examples equivalent, you can define these two aliases: </p> <p> <pre><span style="color:#600277;">leaf</span>&nbsp;::&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">BinaryTree</span>&nbsp;a leaf&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">Leaf</span> <span style="color:#600277;">create</span>&nbsp;::&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">BinaryTree</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">BinaryTree</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">BinaryTree</span>&nbsp;a create&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">Node</span></pre> </p> <p> This enables you to create a binary tree like this: </p> <p> <pre><span style="color:#600277;">source</span>&nbsp;::&nbsp;<span style="color:blue;">BinaryTree</span>&nbsp;Int source&nbsp;<span style="color:#666666;">=</span> &nbsp;&nbsp;&nbsp;&nbsp;create&nbsp;<span style="color:#09885a;">42</span>&nbsp;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;create&nbsp;<span style="color:#09885a;">1337</span>&nbsp;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;leaf&nbsp;<span style="color:#09885a;">0</span>)&nbsp;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;leaf&nbsp;(<span style="color:#666666;">-</span><span style="color:#09885a;">22</span>)))&nbsp;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;leaf&nbsp;<span style="color:#09885a;">100</span>)</pre> </p> <p> As usual you can map the tree using the <code>fmap</code> function: </p> <p> <pre><span style="color:#600277;">dest</span>&nbsp;::&nbsp;<span style="color:blue;">BinaryTree</span>&nbsp;String dest&nbsp;<span style="color:#666666;">=</span>&nbsp;fmap&nbsp;show&nbsp;source</pre> </p> <p> or by using infix notation: </p> <p> <pre><span style="color:#600277;">dest</span>&nbsp;::&nbsp;<span style="color:blue;">BinaryTree</span>&nbsp;String dest&nbsp;<span style="color:#666666;">=</span>&nbsp;show&nbsp;<span style="color:#666666;">&lt;$&gt;</span>&nbsp;source</pre> </p> <p> The <code>&lt;$&gt;</code> operator is an alias for <code>fmap</code>. </p> <h3 id="a0698e17ebc5402a9ce2b9e93dcf581a"> F# <a href="#a0698e17ebc5402a9ce2b9e93dcf581a" title="permalink">#</a> </h3> <p> As usual, <a href="https://fsharp.org">F#</a> lies somewhere between the extremes of C# and Haskell, although it's closer to Haskell in simplicity. The type declaration is similar: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;<span style="color:teal;">BinaryTree</span>&lt;&#39;a&gt;&nbsp;= |&nbsp;<span style="color:navy;">Node</span>&nbsp;<span style="color:blue;">of</span>&nbsp;(&#39;a&nbsp;*&nbsp;<span style="color:teal;">BinaryTree</span>&lt;&#39;a&gt;&nbsp;*&nbsp;<span style="color:teal;">BinaryTree</span>&lt;&#39;a&gt;) |&nbsp;<span style="color:navy;">Leaf</span>&nbsp;<span style="color:blue;">of</span>&nbsp;&#39;a</pre> </p> <p> Unlike Haskell, however, F# doesn't have any built-in functor awareness, so you'll have to implement the <em>map</em> function yourself: </p> <p> <pre><span style="color:green;">//&nbsp;(&#39;a&nbsp;-&gt;&nbsp;&#39;b)&nbsp;-&gt;&nbsp;BinaryTree&lt;&#39;a&gt;&nbsp;-&gt;&nbsp;BinaryTree&lt;&#39;b&gt;</span> <span style="color:blue;">let</span>&nbsp;<span style="color:blue;">rec</span>&nbsp;<span style="color:navy;">map</span>&nbsp;<span style="color:navy;">f</span>&nbsp;=&nbsp;<span style="color:blue;">function</span> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:navy;">Node</span>&nbsp;(x,&nbsp;left,&nbsp;right)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:navy;">Node</span>&nbsp;(<span style="color:navy;">f</span>&nbsp;x,&nbsp;<span style="color:navy;">map</span>&nbsp;<span style="color:navy;">f</span>&nbsp;left,&nbsp;<span style="color:navy;">map</span>&nbsp;<span style="color:navy;">f</span>&nbsp;right) &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:navy;">Leaf</span>&nbsp;x&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:navy;">Leaf</span>&nbsp;(<span style="color:navy;">f</span>&nbsp;x)</pre> </p> <p> Notice that you have to use the <code>rec</code> keyword in order to make <code>map</code> recursive. Instead of having to create a new helper class, and all the byzantine interactions required by the Visitor design pattern, the implementation uses simple pattern matching to achieve the same goal. In the <code>Node</code> case, it uses <code>f</code> to translate <code>x</code>, and recursively calls itself on <code>left</code> and <code>right</code>. In the <code>Leaf</code> case, it simply returns a new <code>Leaf</code> value with <code>x</code> translated by <code>f</code>. </p> <p> Create helper functions to keep all three examples aligned: </p> <p> <pre><span style="color:green;">//&nbsp;&#39;a&nbsp;-&gt;&nbsp;BinaryTree&lt;&#39;a&gt;</span> <span style="color:blue;">let</span>&nbsp;<span style="color:navy;">leaf</span>&nbsp;=&nbsp;<span style="color:navy;">Leaf</span> <span style="color:green;">//&nbsp;&#39;a&nbsp;-&gt;&nbsp;BinaryTree&lt;&#39;a&gt;&nbsp;-&gt;&nbsp;BinaryTree&lt;&#39;a&gt;&nbsp;-&gt;&nbsp;BinaryTree&lt;&#39;a&gt;</span> <span style="color:blue;">let</span>&nbsp;<span style="color:navy;">create</span>&nbsp;x&nbsp;left&nbsp;right&nbsp;=&nbsp;<span style="color:navy;">Node</span>&nbsp;(x,&nbsp;left,&nbsp;right)</pre> </p> <p> You can now create a binary tree of integers: </p> <p> <pre><span style="color:green;">//&nbsp;BinaryTree&lt;int&gt;</span> <span style="color:blue;">let</span>&nbsp;source&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:teal;">BinaryTree</span>.<span style="color:navy;">create</span>&nbsp;42&nbsp;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:teal;">BinaryTree</span>.<span style="color:navy;">create</span>&nbsp;1337&nbsp;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:teal;">BinaryTree</span>.<span style="color:navy;">leaf</span>&nbsp;0)&nbsp;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:teal;">BinaryTree</span>.<span style="color:navy;">leaf</span>&nbsp;-22))&nbsp;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:teal;">BinaryTree</span>.<span style="color:navy;">leaf</span>&nbsp;100)</pre> </p> <p> which you can translate like this: </p> <p> <pre><span style="color:green;">//&nbsp;BinaryTree&lt;string&gt;</span> <span style="color:blue;">let</span>&nbsp;dest&nbsp;=&nbsp;source&nbsp;|&gt;&nbsp;<span style="color:teal;">BinaryTree</span>.<span style="color:navy;">map</span>&nbsp;<span style="color:navy;">string</span></pre> </p> <p> Here, all of the above functions are defined in a module named <code>BinaryTree</code>. </p> <h3 id="cd79db20d2e24587be91ade6ae956b0e"> First functor law <a href="#cd79db20d2e24587be91ade6ae956b0e" title="permalink">#</a> </h3> <p> The <code>Select</code> method obeys the first functor law. As usual, it's proper computer-science work to actually prove that, but you can write some tests to demonstrate the first functor law for the <code>IBinaryTree&lt;T&gt;</code> interface. In this article, you'll see a few parametrised tests written with <a href="https://xunit.github.io">xUnit.net</a>. First, you can define some reusable trees as test input: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:blue;">object</span>[]&gt;&nbsp;Trees { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">get</span> &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">yield</span>&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(0)&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">yield</span>&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>[]&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Create(-3, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(2), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(99))&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">yield</span>&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>[]&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Create(42, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Create(1337, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(0), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(-22)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(100))&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">yield</span>&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>[]&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Create(-927, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(2), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Create(211, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(88), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(132)))&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">yield</span>&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>[]&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Create(111, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Create(-336, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(113), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(-432)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Create(1299, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(-32), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">BinaryTree</span>.Leaf(773)))&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> This is just a collection of five small binary trees that can be used as input for parametrised tests. The first tree is only a single node - the simplest tree you can make with the <code>IBinaryTree&lt;T&gt;</code> API. </p> <p> You can use this static property as a source of input for parametrised tests. Here's one that demonstrates that the first functor law holds: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">MemberData</span>(<span style="color:blue;">nameof</span>(Trees))] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;FirstFunctorLaw(<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;tree) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(tree,&nbsp;tree.Select(x&nbsp;=&gt;&nbsp;x)); }</pre> </p> <p> Here, I chose to implement the identity function as an anonymous lambda expression. In contrast, in a <a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">previous article</a>, I explicitly declared a function variable and called it <code>id</code>. Those two ways to express the identity function are equivalent. </p> <p> As always, I'd like to emphasise that this test doesn't <em>prove</em> that <code>IBinaryTree&lt;T&gt;</code> obeys the first functor law. It only demonstrates that the law holds for those five examples. </p> <h3 id="f68059de38e24d0b9745b7e8071354d1"> Second functor law <a href="#f68059de38e24d0b9745b7e8071354d1" title="permalink">#</a> </h3> <p> Like the above example, you can also write a parametrised test that demonstrates that <code>IBinaryTree&lt;T&gt;</code> obeys the second functor law. You can reuse the <code>Trees</code> test case source for that test: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">MemberData</span>(<span style="color:blue;">nameof</span>(Trees))] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SecondFunctorLaw(<span style="color:#2b91af;">IBinaryTree</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;tree) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;g(<span style="color:blue;">int</span>&nbsp;i)&nbsp;=&gt;&nbsp;i.ToString(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">bool</span>&nbsp;f(<span style="color:blue;">string</span>&nbsp;s)&nbsp;=&gt;&nbsp;s.Length&nbsp;%&nbsp;2&nbsp;==&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(tree.Select(g).Select(f),&nbsp;tree.Select(i&nbsp;=&gt;&nbsp;f(g(i)))); }</pre> </p> <p> This test defines two local functions, <code>f</code> and <code>g</code>. Instead of explicitly declaring the functions as <code>Func</code> variables, this test uses a (relatively) new C# feature called <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions">local functions</a>. </p> <p> Again, while the test doesn't prove anything, it demonstrates that for the five test cases, it doesn't matter if you project the <code>tree</code> in one or two steps. </p> <h3 id="cb5749ec27474647b6d96679c5d1d0ce"> Summary <a href="#cb5749ec27474647b6d96679c5d1d0ce" title="permalink">#</a> </h3> <p> Statically typed functional languages like F# and Haskell enable you to define <a href="https://en.wikipedia.org/wiki/Tagged_union">sum types</a>: types that encode a selection of mutually exclusive cases. Combined with pattern matching, it's easy to deal with values that can be one of several non-polymorphic cases. Object-oriented languages like C# or Java don't have good support for this type of data structure. Object-oriented programmers often resort to using type hierarchies, but this requires down-casting in order to work. It also comes with the disadvantage that with type hierarchies, the hierarchy is extensible, which means that as an implementer, you never know if you've handled all sub-types. <a href="http://blog.ploeh.dk/2018/06/25/visitor-as-a-sum-type">The Visitor design pattern is a way to model sum types in object-oriented programming</a>, although it tends to be verbose. </p> <p> Nevertheless, if you have a generic type that models a set of mutually exclusive cases, it just may be a functor. In Haskell, you can make such a type a <code>Functor</code> with a mere declaration. In C#, you have to write considerable amounts of code. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/08/20/reactive-functor">Reactive functor</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. A Tree functor http://blog.ploeh.dk/2018/08/06/a-tree-functor 2018-08-06T06:00:00+00:00 Mark Seemann <div id="post"> <p> <em>A generalised tree object as a functor. Another functor example for object-oriented programmers.</em> </p> <p> This article is an instalment in <a href="http://blog.ploeh.dk/2018/03/22/functors">an article series about functors</a>. In the <a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">previous article</a>, you saw how to implement the Maybe functor in C#. In this article, you'll get another functor example: a generalised tree (also known as a <em>rose tree</em>). </p> <p> As opposed to a binary tree, any node in a generalised tree can have an arbitrary number of children, including none. </p> <h3 id="19775137ce6b44499b1924c687b1c5e3"> Implementation <a href="#19775137ce6b44499b1924c687b1c5e3" title="permalink">#</a> </h3> <p> The following <code>Tree&lt;T&gt;</code> class can contain objects of the generic type <code>T</code>. Being generic, it's a candidate for a functor, and it does, in fact, turn out to be one: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;:&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">T</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;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;children; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Item&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Tree(<span style="color:#2b91af;">T</span>&nbsp;item,&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;children) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(item&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(item)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(children&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(children)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Item&nbsp;=&nbsp;item; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.children&nbsp;=&nbsp;children; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;Select&lt;<span style="color:#2b91af;">TResult</span>&gt;(<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;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;mappedItem&nbsp;=&nbsp;selector(Item); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;mappedChildren&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">foreach</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;t&nbsp;<span style="color:blue;">in</span>&nbsp;children) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mappedChildren.Add(t.Select(selector)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;(mappedItem,&nbsp;mappedChildren); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">int</span>&nbsp;Count &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">get</span>&nbsp;{&nbsp;<span style="color:blue;">return</span>&nbsp;children.Count;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IEnumerator</span>&lt;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;GetEnumerator() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;children.GetEnumerator(); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IEnumerator</span>&nbsp;<span style="color:#2b91af;">IEnumerable</span>.GetEnumerator() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;children.GetEnumerator(); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;Equals(<span style="color:blue;">object</span>&nbsp;obj) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!(obj&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;other)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;Equals(Item,&nbsp;other.Item) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;&amp;&nbsp;<span style="color:#2b91af;">Enumerable</span>.SequenceEqual(<span style="color:blue;">this</span>,&nbsp;other); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">int</span>&nbsp;GetHashCode() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;Item.GetHashCode()&nbsp;^&nbsp;children.GetHashCode(); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> As is usually the case, you can implement a tree in more than one way. Here, I chose an approach where <code>Tree&lt;T&gt;</code> contains an <code>Item</code> and <em>is</em> a collection of (sub)trees. Notice that the definition is recursive: in addition to its <code>Item</code>, each <code>Tree&lt;T&gt;</code> object also contains a finite collection of other trees. You create leaf nodes with empty collections. </p> <p> This variation uses finite collections (<code>IReadOnlyCollection&lt;T&gt;</code>), but you could also enable infinite trees by instead using potentially infinite sequences (<code>IEnumerable&lt;T&gt;</code>). This would slightly complicate the implementation of the <code>Select</code> method, though, so I decided to leave that as an exercise to the reader. </p> <p> The <code>Select</code> method first translates the contained <code>Item</code> using the <code>selector</code> function, and then recursively calls itself for each sub-tree in <code>children</code>. This method has the desired signature, and furthermore obeys the functor laws, as you'll see later in the article. <code>Tree&lt;T&gt;</code> is a functor. </p> <h3 id="0bb07dad62be418ca8fa0e0d187c00bc"> Usage <a href="#0bb07dad62be418ca8fa0e0d187c00bc" title="permalink">#</a> </h3> <p> While you can create trees directly with the <code>Tree&lt;T&gt;</code> constructor, a few static helper methods makes it smoother: </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;">Tree</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;Leaf&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">T</span>&nbsp;item) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">T</span>&gt;(item,&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">T</span>&gt;[0]); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;Create&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">T</span>&nbsp;item,&nbsp;<span style="color:blue;">params</span>&nbsp;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">T</span>&gt;[]&nbsp;children) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Tree</span>&lt;<span style="color:#2b91af;">T</span>&gt;(item,&nbsp;children); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> This enables you to create a tree like this: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;source&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Create(42, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Create(1337, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Leaf(-3)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Create(7, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Leaf(-99), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Leaf(100), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Leaf(0)));</pre> </p> <p> This is a tree containing integers. You can translate it to a tree containing strings like this: </p> <p> <pre><span style="color:#2b91af;">Tree</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;dest&nbsp;=&nbsp;source.Select(i&nbsp;=&gt;&nbsp;i.ToString()); </pre> </p> <p> or like this: </p> <p> <pre><span style="color:#2b91af;">Tree</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;dest&nbsp;=&nbsp;<span style="color:blue;">from</span>&nbsp;i&nbsp;<span style="color:blue;">in</span>&nbsp;source &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;i.ToString();</pre> </p> <p> In both of these examples, I've explicitly declared the type of <code>dest</code> instead of using the <code>var</code> keyword. There's no practical reason to do this; I only did it to make the type clear to you. </p> <h3 id="1a02c785b313419b9731240c0ee205f8"> Haskell <a href="#1a02c785b313419b9731240c0ee205f8" title="permalink">#</a> </h3> <p> <a href="https://haskell.org">Haskell</a> has a more explicit model of functors, and the language features to support it. The Haskell equivalent to the above <code>Tree&lt;T&gt;</code> class is literally one line of code: </p> <p> <pre><span style="color:blue;">data</span>&nbsp;<span style="color:#dd0000;">Tree</span>&nbsp;a&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">Tree</span>&nbsp;a&nbsp;[<span style="color:#dd0000;">Tree</span>&nbsp;a]&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#a31515;">Show</span>,&nbsp;<span style="color:#a31515;">Eq</span>,&nbsp;<span style="color:#a31515;">Functor</span>) </pre> </p> <p> Notice that the Haskell compiler can automatically derive an implementation of the <code>Functor</code> typeclass, although that does require the <code>DeriveFunctor</code> language extension. </p> <p> You can expend a few more lines of code for utility functions, so that it looks like you're actually programming: </p> <p> <pre><span style="color:#600277;">leaf</span>&nbsp;::&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Tree</span>&nbsp;a leaf&nbsp;x&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">Tree</span>&nbsp;x&nbsp;<span style="color:blue;">[]</span> <span style="color:#600277;">create</span>&nbsp;::&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[<span style="color:blue;">Tree</span>&nbsp;a]&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Tree</span>&nbsp;a create&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">Tree</span></pre> </p> <p> These functions correspond to the static methods on the above <code>Tree</code> class. With them, you can now create a tree: </p> <p> <pre><span style="color:#600277;">source</span>&nbsp;::&nbsp;<span style="color:blue;">Tree</span>&nbsp;Int source&nbsp;<span style="color:#666666;">=</span> &nbsp;&nbsp;create&nbsp;<span style="color:#09885a;">42</span>&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;create&nbsp;<span style="color:#09885a;">1337</span>&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;leaf&nbsp;(<span style="color:#666666;">-</span><span style="color:#09885a;">3</span>)], &nbsp;&nbsp;&nbsp;&nbsp;create&nbsp;<span style="color:#09885a;">7</span>&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;leaf&nbsp;(<span style="color:#666666;">-</span><span style="color:#09885a;">99</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;leaf&nbsp;<span style="color:#09885a;">100</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;leaf&nbsp;<span style="color:#09885a;">0</span>]]</pre> </p> <p> You can translate such a tree of integers to a tree of strings with the <code>fmap</code> function: </p> <p> <pre><span style="color:#600277;">dest</span>&nbsp;::&nbsp;<span style="color:blue;">Tree</span>&nbsp;String dest&nbsp;<span style="color:#666666;">=</span>&nbsp;fmap&nbsp;show&nbsp;source</pre> </p> <p> or with the infix operator: </p> <p> <pre><span style="color:#600277;">dest</span>&nbsp;::&nbsp;<span style="color:blue;">Tree</span>&nbsp;String dest&nbsp;<span style="color:#666666;">=</span>&nbsp;show&nbsp;<span style="color:#666666;">&lt;$&gt;</span>&nbsp;source</pre> </p> <p> The <code>&lt;$&gt;</code> operator is an alias for <code>fmap</code>. </p> <h3 id="32fc2e88a44f41a0a924c57b47d41aa6"> F# <a href="#32fc2e88a44f41a0a924c57b47d41aa6" title="permalink">#</a> </h3> <p> In <a href="https://fsharp.org">F#</a>, the type definition has the same structure as in Haskell: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;<span style="color:teal;">Tree</span>&lt;&#39;a&gt;&nbsp;=&nbsp;<span style="color:navy;">Tree</span>&nbsp;<span style="color:blue;">of</span>&nbsp;(&#39;a&nbsp;*&nbsp;<span style="color:teal;">Tree</span>&lt;&#39;a&gt;&nbsp;<span style="color:teal;">list</span>) </pre> </p> <p> Unlike Haskell, however, F# doesn't have any built-in functor awareness, so you'll have to implement the <em>map</em> function yourself: </p> <p> <pre><span style="color:green;">//&nbsp;(&#39;a&nbsp;-&gt;&nbsp;&#39;b)&nbsp;-&gt;&nbsp;Tree&lt;&#39;a&gt;&nbsp;-&gt;&nbsp;Tree&lt;&#39;b&gt;</span> <span style="color:blue;">let</span>&nbsp;<span style="color:blue;">rec</span>&nbsp;<span style="color:navy;">map</span>&nbsp;<span style="color:navy;">f</span>&nbsp;(<span style="color:navy;">Tree</span>&nbsp;(x,&nbsp;children))&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;mappedX&nbsp;=&nbsp;<span style="color:navy;">f</span>&nbsp;x &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;mappedChildren&nbsp;=&nbsp;children&nbsp;|&gt;&nbsp;<span style="color:teal;">List</span>.<span style="color:navy;">map</span>&nbsp;(<span style="color:navy;">map</span>&nbsp;<span style="color:navy;">f</span>) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:navy;">Tree</span>&nbsp;(mappedX,&nbsp;mappedChildren)</pre> </p> <p> Notice that you have to use the <code>rec</code> keyword in order to make <code>map</code> recursive. The implementation is similar to the C# code: first use <code>f</code> to map the contained item, and then recursively map the children. </p> <p> To keep all three examples equivalent, you can also define utility functions: </p> <p> <pre><span style="color:green;">//&nbsp;&#39;a&nbsp;-&gt;&nbsp;Tree&lt;&#39;a&gt;</span> <span style="color:blue;">let</span>&nbsp;<span style="color:navy;">leaf</span>&nbsp;x&nbsp;=&nbsp;<span style="color:navy;">Tree</span>&nbsp;(x,&nbsp;<span style="color:teal;">List</span>.empty) <span style="color:green;">//&nbsp;&#39;a&nbsp;-&gt;&nbsp;Tree&lt;&#39;a&gt;&nbsp;list&nbsp;-&gt;&nbsp;Tree&lt;&#39;a&gt;</span> <span style="color:blue;">let</span>&nbsp;<span style="color:navy;">create</span>&nbsp;x&nbsp;children&nbsp;=&nbsp;<span style="color:navy;">Tree</span>&nbsp;(x,&nbsp;children)</pre> </p> <p> This enables you to create a tree like this: </p> <p> <pre><span style="color:green;">//&nbsp;Tree&lt;int&gt;</span> <span style="color:blue;">let</span>&nbsp;source&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:teal;">Tree</span>.<span style="color:navy;">create</span>&nbsp;42&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:teal;">Tree</span>.<span style="color:navy;">create</span>&nbsp;1337&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:teal;">Tree</span>.<span style="color:navy;">leaf</span>&nbsp;-3] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:teal;">Tree</span>.<span style="color:navy;">create</span>&nbsp;7&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:teal;">Tree</span>.<span style="color:navy;">leaf</span>&nbsp;-99 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:teal;">Tree</span>.<span style="color:navy;">leaf</span>&nbsp;100 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:teal;">Tree</span>.<span style="color:navy;">leaf</span>&nbsp;0]]</pre> </p> <p> which you can translate like this: </p> <p> <pre><span style="color:green;">//&nbsp;Tree&lt;string&gt;</span> <span style="color:blue;">let</span>&nbsp;dest&nbsp;=&nbsp;source&nbsp;|&gt;&nbsp;<span style="color:teal;">Tree</span>.<span style="color:navy;">map</span>&nbsp;<span style="color:navy;">string</span></pre> </p> <p> Here, all of the above functions are defined in a module named <code>Tree</code>. </p> <h3 id="583705522ab34d4da714fcf3aa18ca0f"> First functor law <a href="#583705522ab34d4da714fcf3aa18ca0f" title="permalink">#</a> </h3> <p> The <code>Select</code> method obeys the first functor law. As usual, it's proper computer-science work to actually prove that, but you can write some tests to demonstrate the first functor law for the <code>Tree&lt;T&gt;</code> class. In this article, you'll see a few parametrised tests written with <a href="https://xunit.github.io">xUnit.net</a>. First, you can define some reusable trees as test input: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:blue;">object</span>[]&gt;&nbsp;Trees { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">get</span> &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">yield</span>&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#2b91af;">Tree</span>.Leaf(42)&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">yield</span>&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#2b91af;">Tree</span>.Create(-32,&nbsp;<span style="color:#2b91af;">Tree</span>.Leaf(0))&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">yield</span>&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>[]&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Create(99, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Leaf(90), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Leaf(2))&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">yield</span>&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>[]&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Create(99, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Leaf(90), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Create(2, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Leaf(-3)))&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">yield</span>&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>[]&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Create(42, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Create(1337, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Leaf(-3)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Create(7, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Leaf(-99), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Leaf(100), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Tree</span>.Leaf(0)))&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> This is just a collection of five small trees that can be used as input for parametrised tests. The first tree is only a single node - the simplest tree you can make with the <code>Tree&lt;T&gt;</code> class. </p> <p> You can use this static property as a source of input for parametrised tests. Here's one that demonstrates that the first functor law holds: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">MemberData</span>(<span style="color:blue;">nameof</span>(Trees))] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;FirstFunctorLaw(<span style="color:#2b91af;">Tree</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;tree) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(tree,&nbsp;tree.Select(x&nbsp;=&gt;&nbsp;x)); }</pre> </p> <p> Here, I chose to implement the identity function as an anonymous lambda expression. In contrast, in the <a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">previous article</a>, I explicitly declared a function variable and called it <code>id</code>. Those two ways to express the identity function are equivalent. </p> <p> As always, I'd like to emphasise that this test doesn't <em>prove</em> that <code>Tree&lt;T&gt;</code> obeys the first functor law. It only demonstrates that the law holds for those five examples. </p> <h3 id="6fdcdebc30e5453ea119652b50f2d8f3"> Second functor law <a href="#6fdcdebc30e5453ea119652b50f2d8f3" title="permalink">#</a> </h3> <p> Like the above example, you can also write a parametrised test that demonstrates that <code>Tree&lt;T&gt;</code> obeys the second functor law. You can reuse the <code>Trees</code> test case source for that test: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">MemberData</span>(<span style="color:blue;">nameof</span>(Trees))] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SecondFunctorLaw(<span style="color:#2b91af;">Tree</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;tree) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;g(<span style="color:blue;">int</span>&nbsp;i)&nbsp;=&gt;&nbsp;i.ToString(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">bool</span>&nbsp;f(<span style="color:blue;">string</span>&nbsp;s)&nbsp;=&gt;&nbsp;s.Length&nbsp;%&nbsp;2&nbsp;==&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(tree.Select(g).Select(f),&nbsp;tree.Select(i&nbsp;=&gt;&nbsp;f(g(i)))); }</pre> </p> <p> This test defines two local functions, <code>f</code> and <code>g</code>. Instead of explicitly declaring the functions as <code>Func</code> variables, this test uses a (relatively) new C# feature called <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions">local functions</a>. </p> <p> Again, while the test doesn't prove anything, it demonstrates that for the five test cases, it doesn't matter if you project the <code>tree</code> in one or two steps. </p> <h3 id="2a3fb6d8a4c24b759ca234ba5cda64d7"> Summary <a href="#2a3fb6d8a4c24b759ca234ba5cda64d7" title="permalink">#</a> </h3> <p> This was the second example of a functor implemented in a statically typed object-oriented language, but contrasted with implementations in statically typed functional languages. The concept of a functor translates without much loss of fidelity, but you'll have to write more verbose code. A language like C# isn't optimised for functors or their like; Haskell and F# are. </p> <p> The purpose of this article series is to show enough examples of functors that you should start to see a pattern. Keep in mind, though, that a functor isn't a design pattern. It's a mathematical concept. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/08/13/a-visitor-functor">A Visitor functor</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Flattening arrow code using a stack of monads http://blog.ploeh.dk/2018/07/30/flattening-arrow-code-using-a-stack-of-monads 2018-07-30T06:05:00+00:00 Mark Seemann <div id="post"> <p> <em>Flatten arrow code with a stack of monads. A horrible example in C#.</em> </p> <p> In the <a href="http://blog.ploeh.dk/2018/07/24/dependency-injection-revisited">previous article</a>, you saw how to refactor an injected dependency to a <a href="https://en.wikipedia.org/wiki/Visitor_pattern">Visitor</a> that implements a free monad. One remaining problem is that some of the code tends towards the <a href="http://wiki.c2.com/?ArrowAntiPattern">Arrow anti-pattern</a>. In this article, you'll see how elegantly you can deal with this in <a href="https://www.haskell.org">Haskell</a>, how it translates to slightly more verbose <a href="http://fsharp.org">F#</a> code, but how, even though it does translate all the way to C#, it stops being nice along the way. </p> <p> All code for this article is <a href="https://github.com/ploeh/dependency-injection-revisited">available on GitHub</a>. </p> <h3 id="75b2c37430424507a5dd5118796a13eb"> Arrow code <a href="#75b2c37430424507a5dd5118796a13eb" title="permalink">#</a> </h3> <p> This is the problematic code: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:blue;">int</span>?&gt;&nbsp;TryAccept(<span style="color:#2b91af;">Reservation</span>&nbsp;reservation) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">ReservationsProgram</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.IsReservationInFuture(reservation) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.SelectMany(isInFuture&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!isInFuture) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Pure</span>&lt;<span style="color:blue;">int</span>?&gt;(<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;">ReservationsProgram</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.ReadReservations(reservation.Date) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.SelectMany(reservations&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;reservedSeats&nbsp;=&nbsp;reservations.Sum(r&nbsp;=&gt;&nbsp;r.Quantity); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(Capacity&nbsp;&lt;&nbsp;reservedSeats&nbsp;+&nbsp;reservation.Quantity) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Pure</span>&lt;<span style="color:blue;">int</span>?&gt;(<span style="color:blue;">null</span>); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;reservation.IsAccepted&nbsp;=&nbsp;<span style="color:blue;">true</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">ReservationsProgram</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Create(reservation) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Select(x&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:blue;">int</span>?(x)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); }</pre> </p> <p> Perhaps it doesn't look <em>that</em> bad, but I think that that's mostly a result of the original example being as simple as it is. After all, the original example code started out like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">int</span>?&nbsp;TryAccept(<span style="color:#2b91af;">Reservation</span>&nbsp;reservation) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!ReservationsRepository.IsReservationInFuture(reservation)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;reservedSeats&nbsp;=&nbsp;ReservationsRepository &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.ReadReservations(reservation.Date) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Sum(r&nbsp;=&gt;&nbsp;r.Quantity); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(Capacity&nbsp;&lt;&nbsp;reservedSeats&nbsp;+&nbsp;reservation.Quantity) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;reservation.IsAccepted&nbsp;=&nbsp;<span style="color:blue;">true</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;ReservationsRepository.Create(reservation); }</pre> </p> <p> The <a href="https://en.wikipedia.org/wiki/Cyclomatic_complexity">cyclomatic complexity</a> of this method could be as low as <em>3</em>, so if this was real production code, there'd be no reason to refactor it. As with most of my articles, however, you have to think of this example problem as a stand-in for something more complicated. </p> <p> If you take a second look at the top version (which is actually the later version), I hope you'll agree that the change has harmed the code. In general, it's more noisy, and it shows a clear tendency towards the dreaded Arrow anti-pattern. Again, it may not look that bad here, but if you imagine that we're looking at a stand-in for a much worse problem, I hope you can see how this could quickly become unsustainable. </p> <p> Part of the problem is that while C# has <em>some</em> syntactic sugar for monads, you can't branch inside a query expression, so instead it seems as though you're stuck with such nested closures. </p> <h3 id="b7ed2b8a51d745d580a7ceaea376923a"> First F# attempt <a href="#b7ed2b8a51d745d580a7ceaea376923a" title="permalink">#</a> </h3> <p> F#, on the other hand, doesn't have that limitation. In F#, you <em>can</em> branch inside of <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/computation-expressions">computation expressions</a>, so would that address the problem? Unfortunately, that's not the whole story. Here's an attempt at writing equivalent code in F#, using a custom <code>reservations</code> computation expression: </p> <p> <pre><span style="color:green;">//&nbsp;int&nbsp;-&gt;&nbsp;Reservation&nbsp;-&gt;&nbsp;ReservationsProgram&lt;int&nbsp;option&gt;</span> <span style="color:blue;">let</span>&nbsp;tryAccept&nbsp;capacity&nbsp;reservation&nbsp;=&nbsp;reservations&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;isInFuture&nbsp;=&nbsp;isReservationInFuture&nbsp;reservation &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;not&nbsp;isInFuture &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">then</span>&nbsp;<span style="color:blue;">return</span>&nbsp;None &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">else</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;reservations&nbsp;=&nbsp;readReservations&nbsp;reservation.Date &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;reservedSeats&nbsp;=&nbsp;List.sumBy&nbsp;(<span style="color:blue;">fun</span>&nbsp;r&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;r.Quantity)&nbsp;reservations &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(capacity&nbsp;&lt;&nbsp;reservedSeats&nbsp;+&nbsp;reservation.Quantity) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">then</span>&nbsp;<span style="color:blue;">return</span>&nbsp;None &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">else</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;reservationId&nbsp;=&nbsp;create&nbsp;{&nbsp;reservation&nbsp;<span style="color:blue;">with</span>&nbsp;IsAccepted&nbsp;=&nbsp;<span style="color:blue;">true</span>&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;Some&nbsp;reservationId&nbsp;}</pre> </p> <p> While this is, in my opinion, more readable than the C# code, it doesn't successfully address the Arrow anti-pattern. While it's perfectly possible to branch (that is: use <code>if</code>, <code>then</code>, and <code>else</code>) inside a computation expression, we run into another problem. In statement-based languages like C# and Java, you can use <a href="http://wiki.c2.com/?GuardClause">Guard Clauses</a> to return early, as the original, pretty C# example demonstrates. In expression-based languages like F# and Haskell, on the other hand, any <code>if</code> branch must have a corresponding <code>else</code> branch, and both branches must return a value of the same type. This restriction forces the above F# code into the same Arrow shape as the problematic C# code. </p> <p> Languages like F# and Haskell would be poor languages, though, if they didn't have ways to address problems like this one. </p> <h3 id="d1002454f4484ce4aff95a5bec705d71"> Flattening with MaybeT <a href="#d1002454f4484ce4aff95a5bec705d71" title="permalink">#</a> </h3> <p> While it already feels unpleasant to write F# code like the above, writing similar code in Haskell would be figuratively painful. In Haskell, however, you essentially just change the return type of your function, pull in some standard library functions, and before you know it, you have nice flat code, with nary an Arrow in sight: </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> One of the notable traits of Haskell is that, because of its high-level abstractions, changing the type of an expression can change its behaviour. In this case, I decided to add a <code>MaybeT</code> to the <code>ReservationsProgram Int</code> return type. This means that not only does the following code take place inside the <code>ReservationsProgram</code> free monad, it takes place inside a stack of monads. In this case, the stack consists of <code>Maybe</code> and <code>ReservationsProgram</code>. </p> <p> What this means is that you can use the built-in <code>guard</code> function to short-circuit the program if the guards fail. Yes, these are <em>literally</em> guard clauses! </p> <p> Not only does this address the Arrow anti-pattern, it completely flattens the code so that the happy path is emphasised. </p> <h3 id="8fc51002d11d43779d9b3887b9b08e3c"> Stacking monads in F# <a href="#8fc51002d11d43779d9b3887b9b08e3c" title="permalink">#</a> </h3> <p> While Haskell comes with built-in monad transformers that enable you to declaratively stack monads, you'll have to do it manually in F#. It's still possible, though. All it takes to stack <code>ReservationsProgram</code> and <code>option</code> is something like this: </p> <p> <pre><span style="color:green;">//&nbsp;(&#39;a&nbsp;-&gt;&nbsp;ReservationsProgram&lt;&#39;b&nbsp;option&gt;)&nbsp;-&gt;&nbsp;ReservationsProgram&lt;&#39;a&nbsp;option&gt;&nbsp;-&gt;</span> <span style="color:green;">//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ReservationsProgram&lt;&#39;b&nbsp;option&gt;</span> <span style="color:blue;">let</span>&nbsp;bind&nbsp;f&nbsp;x&nbsp;=&nbsp;reservations&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;x&#39;&nbsp;=&nbsp;x &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;x&#39;&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;Some&nbsp;x&#39;&#39;&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">return!</span>&nbsp;f&nbsp;x&#39;&#39; &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;None&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">return</span>&nbsp;None&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp; <span style="color:blue;">type</span>&nbsp;ReservationsOptionBuilder&nbsp;()&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">member</span>&nbsp;this.Bind&nbsp;(x,&nbsp;f)&nbsp;=&nbsp;bind&nbsp;f&nbsp;x &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">member</span>&nbsp;this.Return&nbsp;x&nbsp;=&nbsp;Pure&nbsp;(Some&nbsp;x) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">member</span>&nbsp;this.ReturnFrom&nbsp;x&nbsp;=&nbsp;x &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">member</span>&nbsp;this.Zero&nbsp;()&nbsp;=&nbsp;Pure&nbsp;(Some&nbsp;()) <span style="color:blue;">let</span>&nbsp;reservationsOption&nbsp;=&nbsp;ReservationsOptionBuilder&nbsp;()</pre> </p> <p> This stack of monads specifically handles the combination where a <code>ReservationsProgram</code> contains an <code>option</code> value. It considers the continuation value <code>x'</code> produced by the previous step in a <code>ReservationsProgram</code>, and only continues with <code>f</code> if the value is a <code>Some</code> value. Just like <code>option</code> normally works, it short-circuits further processing if the value is a <code>None</code> value. </p> <p> While F# doesn't have a general-purpose <code>guard</code> function, you can easily write one for this particular stack of monads: </p> <p> <pre><span style="color:green;">//&nbsp;bool&nbsp;-&gt;&nbsp;ReservationsProgram&lt;unit&nbsp;option&gt;</span> <span style="color:blue;">let</span>&nbsp;guard&nbsp;=&nbsp;<span style="color:blue;">function</span> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:blue;">true</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;Pure&nbsp;(Some&nbsp;()) &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:blue;">false</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;Pure&nbsp;None</pre> </p> <p> This function takes a Boolean value as input, and returns <code>Pure (Some ())</code> when the value is <code>true</code>, and <code>Pure None</code> otherwise. While this seems weird at first glance, this is essentially what Haskell's <code>guard</code> does in the above code listing. The point is that <code>Pure None</code> short-circuits further processing, while <code>Pure (Some ())</code> allows the program to continue, as per the above <code>bind</code> function. </p> <p> You can now write a flattened version of <code>tryAccept</code> </p> <p> <pre><span style="color:green;">//&nbsp;int&nbsp;-&gt;&nbsp;Reservation&nbsp;-&gt;&nbsp;ReservationsProgram&lt;int&nbsp;option&gt;</span> <span style="color:blue;">let</span>&nbsp;tryAccept&nbsp;capacity&nbsp;reservation&nbsp;=&nbsp;reservationsOption&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">do!</span>&nbsp;ReservationsOption.bind&nbsp;guard&nbsp;&lt;|&nbsp;isReservationInFuture&nbsp;reservation &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;reservations&nbsp;=&nbsp;readReservations&nbsp;reservation.Date &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;reservedSeats&nbsp;=&nbsp;List.sumBy&nbsp;(<span style="color:blue;">fun</span>&nbsp;r&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;r.Quantity)&nbsp;reservations &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">do!</span>&nbsp;guard&nbsp;(reservedSeats&nbsp;+&nbsp;reservation.Quantity&nbsp;&lt;=&nbsp;capacity) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return!</span>&nbsp;create&nbsp;{&nbsp;reservation&nbsp;<span style="color:blue;">with</span>&nbsp;IsAccepted&nbsp;=&nbsp;<span style="color:blue;">true</span>&nbsp;}&nbsp;}</pre> </p> <p> Notice that the type of the function doesn't change. It still returns a <code>ReservationsProgram&lt;int&nbsp;option&gt;</code>, but the implementation is different. Instead of explicitly dealing with branching in a <code>reservations</code> computation expression, it implicitly deals with it in the composed <code>reservationsOption</code> computation expression. </p> <p> Using the specialised <code>guard</code> function doesn't look as pretty as in Haskell, but it gets the job done. </p> <h3 id="49439df4397f454db0e13e9ffabde989"> Maybe as a Visitor <a href="#49439df4397f454db0e13e9ffabde989" title="permalink">#</a> </h3> <p> Can you do the same in C#? Yes, sort of, but it'll be ugly. </p> <p> As a first step, you'll need a Maybe monad, as this isn't a built-in type in C#. While I'd <a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">typically prefer a simpler implementation</a>, since we're already looking at <a href="http://blog.ploeh.dk/2018/05/22/church-encoding">Church-encoded sum types</a>, let's take <a href="http://blog.ploeh.dk/2018/06/04/church-encoded-maybe">the Church-encoded Maybe implementation</a>, and <a href="http://blog.ploeh.dk/2018/06/25/visitor-as-a-sum-type">refactor it to a Visitor</a>. The <code>IMaybe&lt;T&gt;</code> interface is simply this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Accept&lt;<span style="color:#2b91af;">TResult</span>&gt;(<span style="color:#2b91af;">IMaybeVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;visitor); }</pre> </p> <p> The Visitor is defined like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IMaybeVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;VisitNothing&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;VisitJust(<span style="color:#2b91af;">T</span>&nbsp;just); }</pre> </p> <p> This is, hopefully, not terribly surprising. There's two cases: <em>just</em> and <em>nothing</em>, and only the <em>just</em> case has a value associated. While I'm not going to walk you through all the details, this version of <code>IMaybe&lt;T&gt;</code> is still a monad: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;SelectMany&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;">IMaybe</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;">IMaybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;selector) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;source.Accept(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SelectManyMaybeVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;(selector)); }</pre> </p> <p> If you want to see how <code>SelectManyMaybeVisitor&lt;T, TResult&gt;</code> is implemented, you can see it in the code repository, but otherwise, it's also a good exercise to see if you can puzzle it out yourself. </p> <h3 id="2db9614a8e674839b92ffe26aa4fd722"> Stacking Reservations and Maybe <a href="#2db9614a8e674839b92ffe26aa4fd722" title="permalink">#</a> </h3> <p> You already have the <code>IReservationsProgram&lt;T&gt;</code> and <code>IMaybe&lt;T&gt;</code> monads. Now you just need to stack them, just like the above F# code: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;SelectMany&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;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;&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;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;&gt;&nbsp;selector) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;source.SelectMany(x&nbsp;=&gt;&nbsp;x.Accept(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SelectManyMaybeVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;(selector))); } <span style="color:blue;">private</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">SelectManyMaybeVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;: &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IMaybeVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;&gt;&nbsp;selector; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;SelectManyMaybeVisitor(<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;&gt;&nbsp;selector) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.selector&nbsp;=&nbsp;selector; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;VisitNothing &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">get</span>&nbsp;{&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Pure</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Nothing</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;());&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;VisitJust(<span style="color:#2b91af;">T</span>&nbsp;just) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.selector(just); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Just like in the F# code, you can write the code inside of the <code>IReservationsProgram&lt;T&gt;</code> monad. To do that, you call <code>SelectMany</code> on <code>source</code>. The <code>x</code> in that lambda expression is a <code>IMaybe&lt;T&gt;</code> value, so in order to be able to proceed, you'll have to call its <code>Accept</code> method and pass it a Visitor. </p> <p> The overall signature of the outer <code>SelectMany</code> method is fixed. This is, after all, the monadic <em>bind</em> function, so you know that the return type must be <code>IReservationsProgram&lt;IMaybe&lt;TResult&gt;&gt;</code>. Therefore, this must be the second type argument of the Visitor that you pass to <code>Accept</code>, so the Visitor must have the type <code>IMaybeVisitor&lt;T, IReservationsProgram&lt;IMaybe&lt;TResult&gt;&gt;&gt;</code>. From there, it's 'just' a matter of figuring out how to implement <code>VisitNothing</code> and <code>VisitJust</code>. </p> <p> In the <code>VisitNothing</code> case, you simply return a <code>new Nothing&lt;TResult&gt;()</code>, but wrapped in a <code>Pure</code> value, so that it becomes an <code>IReservationsProgram&lt;IMaybe&lt;TResult&gt;&gt;</code>, rather than just an <code>IMaybe&lt;TResult&gt;</code>. </p> <p> In the <code>VisitJust</code> case, you'll need the injected <code>selector</code>, which you can simply call with the input argument and return the result. </p> <p> In order to support query expressions, you'll also need this special <code>SelectMany</code> overload: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;SelectMany&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">U</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;&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;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">U</span>&gt;&gt;&gt;&nbsp;k, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">U</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;s) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;source &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.SelectMany(x&nbsp;=&gt;&nbsp;k(x) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.SelectMany(y&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Pure</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Just</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;(s(x,&nbsp;y))))); }</pre> </p> <p> This is merely a weird C# technical detail, so I'm not going to tire you with this. It's not interesting. </p> <h3 id="5835e8214476428281aecae397272859"> Guard <a href="#5835e8214476428281aecae397272859" title="permalink">#</a> </h3> <p> Like the above F# code, you can define a specialised <code>Guard</code> method: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">Unit</span>&gt;&gt;&nbsp;Guard(<span style="color:blue;">bool</span>&nbsp;b) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(b) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Pure</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">Unit</span>&gt;&gt;(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Just</span>&lt;<span style="color:#2b91af;">Unit</span>&gt;(<span style="color:#2b91af;">Unit</span>.Instance)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">else</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Pure</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">Unit</span>&gt;&gt;(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Nothing</span>&lt;<span style="color:#2b91af;">Unit</span>&gt;()); }</pre> </p> <p> It does the same as its F# counterpart, only is it more verbose, and it required me to define a <em>unit</em> type, because C# doesn't have one: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Unit</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Unit</span>&nbsp;Instance&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Unit</span>(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;Unit()&nbsp;{&nbsp;} }</pre> </p> <p> This is simply a <a href="https://en.wikipedia.org/wiki/Singleton_pattern">Singleton</a> that carries no data. It's like <code>void</code>, but can act as a generic return type, which is what we need here. </p> <h3 id="2ea841e8f8e44c0bb48129000568901d"> Do <a href="#2ea841e8f8e44c0bb48129000568901d" title="permalink">#</a> </h3> <p> Finally, in order to be able to set <code>IsAccepted</code> to <code>true</code> and make it look like a function, you can add a <code>Do</code> method: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">Unit</span>&gt;&gt;&nbsp;Do(<span style="color:#2b91af;">Action</span>&nbsp;action) { &nbsp;&nbsp;&nbsp;&nbsp;action(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Pure</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">Unit</span>&gt;&gt;(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Just</span>&lt;<span style="color:#2b91af;">Unit</span>&gt;(<span style="color:#2b91af;">Unit</span>.Instance)); }</pre> </p> <p> This is a nasty piece of impure code, but it'll get the job done. It'd also be possible to refactor to a make the <code>Reservation</code> class immutable, but for this proof of concept code, that's not necessary. It'll be ugly regardless. </p> <p> The point of the method is to enable method chaining in the <a href="https://martinfowler.com/bliki/FluentInterface.html">Fluent style</a>, even while you're mutating state. In general, I'd like to warn against doing something like this, because the entire point of functional programming is to avoid mutating state. It does allow us, however, to reproduce the original behaviour in the top of the article, which also mutates the <code>reservation</code> argument. </p> <h3 id="ce35ac8aae814e00a130ef2370c2f379"> Method chaining <a href="#ce35ac8aae814e00a130ef2370c2f379" title="permalink">#</a> </h3> <p> You can now write <code>TryAccept</code> as an <code>IReservationsProgram&lt;IMaybe&lt;int&gt;&gt;</code> method, instead of <code>IReservationsProgram&lt;int?&gt;</code>. In other words, you replace the <code>int?</code> (<code>Nullable&lt;int&gt;</code>) with <code>IMaybe&lt;int&gt;</code>. This enables you write the entire program as a 'flat' composition, by chaining calls to <code>SelectMany</code> and <code>Select</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:blue;">int</span>&gt;&gt;&nbsp;TryAccept(<span style="color:#2b91af;">Reservation</span>&nbsp;reservation) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">ReservationsProgram</span>.IsReservationInFuture(reservation) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.SelectMany(isInFuture&nbsp;=&gt;&nbsp;<span style="color:#2b91af;">ReservationsProgram</span>.Guard(isInFuture)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.SelectMany((<span style="color:#2b91af;">Unit</span>&nbsp;_)&nbsp;=&gt;&nbsp;<span style="color:#2b91af;">ReservationsProgram</span>.ReadReservations(reservation.Date)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Select(reservations&nbsp;=&gt;&nbsp;reservations.Sum(r&nbsp;=&gt;&nbsp;r.Quantity)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.SelectMany(reservedSeats&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">ReservationsProgram</span>.Guard(reservedSeats&nbsp;+&nbsp;reservation.Quantity&nbsp;&lt;=&nbsp;Capacity)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.SelectMany((<span style="color:#2b91af;">Unit</span>&nbsp;_)&nbsp;=&gt;&nbsp;<span style="color:#2b91af;">ReservationsProgram</span>.Do(()&nbsp;=&gt;&nbsp;{&nbsp;reservation.IsAccepted&nbsp;=&nbsp;<span style="color:blue;">true</span>;&nbsp;})) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.SelectMany((<span style="color:#2b91af;">Unit</span>&nbsp;_)&nbsp;=&gt;&nbsp;<span style="color:#2b91af;">ReservationsProgram</span>.Create(reservation)); }</pre> </p> <p> You start with <code>ReservationsProgram.IsReservationInFuture</code> and continue with <code>SelectMany</code> off of its return value. Inside <code>SelectMany</code>, you then call <code>ReservationsProgram.Guard</code> in order to short-circuit if <code>isInFuture</code> is <code>false</code>. In fact, that step can be reduced to <code>SelectMany(ReservationsProgram.Guard)</code>, using <em>method group</em> syntax. </p> <p> While <code>Guard</code> returns a program containing <code>Unit</code>, you can still continue with <code>SelectMany</code> to call <code>ReservationsProgram.ReadReservations</code>. </p> <p> I'm not going to walk you through the rest of this code, but it works. </p> <h3 id="0b61af0e585e411197e6fc373b9f5989"> Query syntax <a href="#0b61af0e585e411197e6fc373b9f5989" title="permalink">#</a> </h3> <p> If you can write an entire program by chaining <code>SelectMany</code> and <code>Select</code>, chances are you can write it using C# query syntax as well. This turns out to be the case: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:blue;">int</span>&gt;&gt;&nbsp;TryAccept(<span style="color:#2b91af;">Reservation</span>&nbsp;reservation) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;isInFuture&nbsp;<span style="color:blue;">in</span>&nbsp;<span style="color:#2b91af;">ReservationsProgram</span>.IsReservationInFuture(reservation) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;&nbsp;&nbsp;_&nbsp;<span style="color:blue;">in</span>&nbsp;<span style="color:#2b91af;">ReservationsProgram</span>.Guard(isInFuture) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;reservations&nbsp;<span style="color:blue;">in</span>&nbsp;<span style="color:#2b91af;">ReservationsProgram</span>.ReadReservations(reservation.Date) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;reservedSeats&nbsp;=&nbsp;reservations.Sum(r&nbsp;=&gt;&nbsp;r.Quantity) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;&nbsp;__&nbsp;<span style="color:blue;">in</span>&nbsp;<span style="color:#2b91af;">ReservationsProgram</span>.Guard(reservedSeats&nbsp;+&nbsp;reservation.Quantity&nbsp;&lt;=&nbsp;Capacity) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;___&nbsp;<span style="color:blue;">in</span>&nbsp;<span style="color:#2b91af;">ReservationsProgram</span>.Do(()&nbsp;=&gt;&nbsp;{&nbsp;reservation.IsAccepted&nbsp;=&nbsp;<span style="color:blue;">true</span>;&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;id&nbsp;<span style="color:blue;">in</span>&nbsp;<span style="color:#2b91af;">ReservationsProgram</span>.Create(reservation) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;id; }</pre> </p> <p> This is simply the 'sugared' version of the previous code. It's a little more succinct, but whether it's better is subjective at best. I think you'd be challenged to find anyone who'd consider this <a href="http://blog.ploeh.dk/2015/08/03/idiomatic-or-idiosyncratic">idiomatic</a> C# code. </p> <p> It gets the job done, though. It actually works! </p> <p> To be clear, I'm not particularly impressed with the readability of this. I love the Haskell version, but the C# translation isn't my cup of tea. </p> <h3 id="2d58a676ddba402785078b22f8c43a5b"> Conclusion <a href="#2d58a676ddba402785078b22f8c43a5b" title="permalink">#</a> </h3> <p> When I go to meetups and conferences, I often get the chance to talk to people who have read my articles or seen my talks on functional programming. I often get the question whether it's possible to use some of the wonderful F# and Haskell concepts in C#. This article answers such questions. Yes, it's possible, but what's the point? </p> <p> Such code is brittle, because you're dancing on the edge of what C# can do. I had to accept some compromises just to get this proof-of-concept code to work. To add spite to injury, the code is not as readable as idiomatic C#, and it taps into concepts that most C# developers wouldn't be familiar with. </p> <p> I'd expect most C# programmers to consider a code base like this unreadable. In the amount of time it takes to understand and learn the underlying concepts of monads and their syntactic sugar, one can learn a proper functional programming language like F#. Don't try to make C# do something it wasn't designed to do; just use a functional programming language; you can learn that sooner than you'll be able to make sense of this Frankenstein's monster shown here. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Dependency Injection revisited http://blog.ploeh.dk/2018/07/24/dependency-injection-revisited 2018-07-24T07:26:00+00:00 Mark Seemann <div id="post"> <p> <em>Replace Dependency Injection with a Visitor</em> </p> <p> In a previous article, you saw how you can <a href="http://blog.ploeh.dk/2018/06/25/visitor-as-a-sum-type">model any sum type as a Visitor</a>. Does that mean, then, that you can model a free monad as a <a href="https://en.wikipedia.org/wiki/Visitor_pattern">Visitor</a>? </p> <p> Yes, it does. </p> <p> In the <a href="http://blog.ploeh.dk/2017/08/07/f-free-monad-recipe">F# free monad recipe</a>, you saw how to refactor any injected, interface-based dependency to a free monad. Since a free monad is nothing but a recursive <a href="https://en.wikipedia.org/wiki/Tagged_union">sum type</a>, this means that you now have the tools at your disposal to refactor your injected dependencies to a Visitor. </p> <p> To be clear, this is an article exploring the boundaries of what's possible with a language like C#. It's not intended to be an endorsement of a particular way to organise code. A <a href="https://youtu.be/qBYVW4ghMi8">conference talk recording</a> that covers the same example also exists. </p> <h3 id="71b11c7e93f04304ade1093a4a68d437"> Dependency Injection example <a href="#71b11c7e93f04304ade1093a4a68d437" title="permalink">#</a> </h3> <p> I'll walk you through how to do this. We'll start with an example, which, as usual, is about developing an online restaurant reservations system. The code base you'll see here implements the business logic that decides whether or not to accept a reservation request. All code from this article is <a href="https://github.com/ploeh/dependency-injection-revisited">available on GitHub</a>. </p> <p> In order to make the example illustrative, but still manageable, we'll look at a single dependency, defined like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IReservationsRepository</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;This&nbsp;method&nbsp;doesn&#39;t&nbsp;belong&nbsp;on&nbsp;a&nbsp;Repository&nbsp;interface.&nbsp;It&nbsp;ought&nbsp;to&nbsp;be</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;on&nbsp;some&nbsp;sort&nbsp;of&nbsp;ITimeProvider&nbsp;interface,&nbsp;or&nbsp;an&nbsp;extension&nbsp;method</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;thereof,&nbsp;but&nbsp;in&nbsp;order&nbsp;to&nbsp;keep&nbsp;the&nbsp;example&nbsp;refactorings&nbsp;as&nbsp;simple&nbsp;as</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;possible,&nbsp;it&#39;ll&nbsp;go&nbsp;here&nbsp;for&nbsp;demo&nbsp;purposes.</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">bool</span>&nbsp;IsReservationInFuture(<span style="color:#2b91af;">Reservation</span>&nbsp;reservation); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&nbsp;ReadReservations(<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;date); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;Create(<span style="color:#2b91af;">Reservation</span>&nbsp;reservation); }</pre> </p> <p> As the code comment explains, the <code>IsReservationInFuture</code> method doesn't belong on this <code>IReservationsRepository</code> interface. A dedicated 'time provider' dependency would be more appropriate, but as you'll see when you read on, refactoring just one interface to a free monad Visitor is already complicated. Doing it twice would just repeat the process while adding little additional clarity. </p> <p> Apart from <code>IsReservationInFuture</code>, the <code>IReservationsRepository</code> declares <code>ReadReservations</code> for querying the Repository for existing reservations, and <code>Create</code> for adding a new reservation to the Repository. Notice that the <code>Create</code> method violates the <a href="https://en.wikipedia.org/wiki/Command%E2%80%93query_separation">Command Query Separation</a> principle. While <a href="http://blog.ploeh.dk/2014/08/11/cqs-versus-server-generated-ids">better alternatives exist</a>, I decided to design the present example like this because it better illustrates how data could flow through a system. </p> <p> The only consumer of the interface that we're going to consider is this <code>MaîtreD</code> class: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">MaîtreD</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;MaîtreD(<span style="color:blue;">int</span>&nbsp;capacity,&nbsp;<span style="color:#2b91af;">IReservationsRepository</span>&nbsp;reservationsRepository) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Capacity&nbsp;=&nbsp;capacity; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ReservationsRepository&nbsp;=&nbsp;reservationsRepository; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">int</span>?&nbsp;TryAccept(<span style="color:#2b91af;">Reservation</span>&nbsp;reservation) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!ReservationsRepository.IsReservationInFuture(reservation)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;reservedSeats&nbsp;=&nbsp;ReservationsRepository &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.ReadReservations(reservation.Date) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Sum(r&nbsp;=&gt;&nbsp;r.Quantity); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(Capacity&nbsp;&lt;&nbsp;reservedSeats&nbsp;+&nbsp;reservation.Quantity) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;reservation.IsAccepted&nbsp;=&nbsp;<span style="color:blue;">true</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;ReservationsRepository.Create(reservation); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">int</span>&nbsp;Capacity&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IReservationsRepository</span>&nbsp;ReservationsRepository&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} }</pre> </p> <p> This is straightforward example code. First, it queries whether the reservation is in the past, because it makes no sense accepting a reservation in the past. </p> <p> If it gets past that hurdle, the <code>TryAccept</code> method then queries the injected <code>ReservationsRepository</code> for the reservations already recorded on that date, and calculates the sum of the quantities. This produces <code>reservedSeats</code> - the number of already reserved seats. If the restaurant's <code>Capacity</code> (a <a href="http://blog.ploeh.dk/2012/07/02/PrimitiveDependencies">Primitive Dependency</a>) is less than the already reserved seats, plus the requested quantity, the method again rejects the reservation. This time, the reason is that there's insufficient remaining capacity to accept it. </p> <p> Finally, if the <code>reservation</code> makes it past all the guards, <code>IsAccepted</code> is set to <code>true</code>, and the reservation is added to the Repository. Recall that <code>Create</code> returns the ID of the new reservation (presumably a database ID), so that ID is returned from the method. In all other cases, the method returns <code>null</code>. The return type of <code>TryAccept</code> is <code>int?</code> (<code>Nullable&lt;int&gt;</code>), so the <code>int</code> value returned from <code>Create</code> is implicitly converted to <code>int?</code>; the compiler does that. </p> <h3 id="80b1ee4b685949308a619072d4f6f7ba"> Testability <a href="#80b1ee4b685949308a619072d4f6f7ba" title="permalink">#</a> </h3> <p> My original motivation for learning about Dependency Injection was that I did Test-Driven Development. Dependency Injection enables you to <a href="https://martinfowler.com/articles/nonDeterminism.html">make automated tests deterministic</a> by replacing common sources of non-determinism with <a href="https://martinfowler.com/bliki/TestDouble.html">Test Doubles</a>. This is, predictably, also the case here: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">BookingApiTestConventions</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;TryAcceptReturnsReservationIdInHappyPathScenario( &nbsp;&nbsp;&nbsp;&nbsp;[<span style="color:#2b91af;">Frozen</span>]<span style="color:#2b91af;">Mock</span>&lt;<span style="color:#2b91af;">IReservationsRepository</span>&gt;&nbsp;td, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Reservation</span>&nbsp;reservation, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&nbsp;reservations, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">MaîtreD</span>&nbsp;sut, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;excessCapacity, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;expected) { &nbsp;&nbsp;&nbsp;&nbsp;td.Setup(r&nbsp;=&gt;&nbsp;r.IsReservationInFuture(reservation)).Returns(<span style="color:blue;">true</span>); &nbsp;&nbsp;&nbsp;&nbsp;td &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Setup(r&nbsp;=&gt;&nbsp;r.ReadReservations(reservation.Date)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Returns(reservations); &nbsp;&nbsp;&nbsp;&nbsp;td.Setup(r&nbsp;=&gt;&nbsp;r.Create(reservation)).Returns(expected); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;reservedSeats&nbsp;=&nbsp;reservations.Sum(r&nbsp;=&gt;&nbsp;r.Quantity); &nbsp;&nbsp;&nbsp;&nbsp;reservation.IsAccepted&nbsp;=&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;sut&nbsp;=&nbsp;sut.WithCapacity( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;reservedSeats&nbsp;+&nbsp;reservation.Quantity&nbsp;+&nbsp;excessCapacity); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;sut.TryAccept(reservation); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(expected,&nbsp;actual); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.True(reservation.IsAccepted); }</pre> </p> <p> This tests exercises the happy path scenario where the reservation <em>is</em> in the future, and there <em>is</em> enough remaining capacity to accept the request. It uses <a href="https://xunit.github.io">xUnit.net</a> and <a href="https://github.com/moq/moq4">Moq</a> with <a href="https://github.com/AutoFixture/AutoFixture">AutoFixture</a> gluing it all together. </p> <h3 id="42fb1b18c8ba4c928746a109537b2e38"> Database implementation <a href="#42fb1b18c8ba4c928746a109537b2e38" title="permalink">#</a> </h3> <p> It's nice to be able to test the business logic, but ultimately, you'll need your application to be able to store reservations in some sort of persistent storage like a relational database. That's easy, too. Just implement <code>IReservationsRepository</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">SqlReservationsRepository</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IReservationsRepository</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;SqlReservationsRepository(<span style="color:blue;">string</span>&nbsp;connectionString) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.ConnectionString&nbsp;=&nbsp;connectionString; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">string</span>&nbsp;ConnectionString&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;IsReservationInFuture(<span style="color:#2b91af;">Reservation</span>&nbsp;reservation) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>.Now&nbsp;&lt;&nbsp;reservation.Date; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&nbsp;ReadReservations( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;date) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.ReadReservations( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;date.Date, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;date.Date.AddDays(1).AddTicks(-1)); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&nbsp;ReadReservations( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;min, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;max) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;result&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">using</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;conn&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SqlConnection</span>(<span style="color:blue;">this</span>.ConnectionString)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">using</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;cmd&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SqlCommand</span>(readByRangeSql,&nbsp;conn)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cmd.Parameters.Add(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SqlParameter</span>(<span style="color:#a31515;">&quot;@MinDate&quot;</span>,&nbsp;min)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cmd.Parameters.Add(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SqlParameter</span>(<span style="color:#a31515;">&quot;@MaxDate&quot;</span>,&nbsp;max)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;conn.Open(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">using</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;rdr&nbsp;=&nbsp;cmd.ExecuteReader()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">while</span>&nbsp;(rdr.Read()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.Add( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&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;">Reservation</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date&nbsp;=&nbsp;(<span style="color:#2b91af;">DateTimeOffset</span>)rdr[<span style="color:#a31515;">&quot;Date&quot;</span>], &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;(<span style="color:blue;">string</span>)rdr[<span style="color:#a31515;">&quot;Name&quot;</span>], &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Email&nbsp;=&nbsp;(<span style="color:blue;">string</span>)rdr[<span style="color:#a31515;">&quot;Email&quot;</span>], &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Quantity&nbsp;=&nbsp;(<span style="color:blue;">int</span>)rdr[<span style="color:#a31515;">&quot;Quantity&quot;</span>] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;result; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">const</span>&nbsp;<span style="color:blue;">string</span>&nbsp;readByRangeSql&nbsp;=&nbsp;<span style="color:maroon;">@&quot; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;SELECT&nbsp;[Date],&nbsp;[Name],&nbsp;[Email],&nbsp;[Quantity] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;FROM&nbsp;[dbo].[Reservations] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WHERE&nbsp;YEAR(@MinDate)&nbsp;&lt;=&nbsp;YEAR([Date]) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AND&nbsp;MONTH(@MinDate)&nbsp;&lt;=&nbsp;MONTH([Date]) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AND&nbsp;DAY(@MinDate)&nbsp;&lt;=&nbsp;DAY([Date]) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AND&nbsp;YEAR([Date])&nbsp;&lt;=&nbsp;YEAR(@MaxDate) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AND&nbsp;MONTH([Date])&nbsp;&lt;=&nbsp;MONTH(@MaxDate) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AND&nbsp;DAY([Date])&nbsp;&lt;=&nbsp;DAY(@MaxDate)&quot;</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">int</span>&nbsp;Create(<span style="color:#2b91af;">Reservation</span>&nbsp;reservation) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">using</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;conn&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SqlConnection</span>(ConnectionString)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">using</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;cmd&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SqlCommand</span>(createReservationSql,&nbsp;conn)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cmd.Parameters.Add( &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;">SqlParameter</span>(<span style="color:#a31515;">&quot;@Date&quot;</span>,&nbsp;reservation.Date)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cmd.Parameters.Add( &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;">SqlParameter</span>(<span style="color:#a31515;">&quot;@Name&quot;</span>,&nbsp;reservation.Name)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cmd.Parameters.Add( &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;">SqlParameter</span>(<span style="color:#a31515;">&quot;@Email&quot;</span>,&nbsp;reservation.Email)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cmd.Parameters.Add( &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;">SqlParameter</span>(<span style="color:#a31515;">&quot;@Quantity&quot;</span>,&nbsp;reservation.Quantity)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;conn.Open(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;cmd.ExecuteNonQuery(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">const</span>&nbsp;<span style="color:blue;">string</span>&nbsp;createReservationSql&nbsp;=&nbsp;<span style="color:maroon;">@&quot; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;INSERT&nbsp;INTO&nbsp;[dbo].[Reservations]&nbsp;([Date],&nbsp;[Name],&nbsp;[Email],&nbsp;[Quantity]) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;VALUES&nbsp;(@Date,&nbsp;@Name,&nbsp;@Email,&nbsp;@Quantity)&quot;</span>; }</pre> </p> <p> As has been my position for years, I find it easier to write database implementations using .NET's original ADO.NET API than <a href="http://blogs.tedneward.com/post/the-vietnam-of-computer-science">fighting</a> with an <a href="https://en.wikipedia.org/wiki/Object-relational_mapping">ORM</a>. </p> <h3 id="adb81dfa7394423fb07ea0015c2a8c69"> Free monad in F# <a href="#adb81dfa7394423fb07ea0015c2a8c69" title="permalink">#</a> </h3> <p> In order to refactor <code>IReservationsRepository</code> to a free monad, it's illustrative to first see how it would look in <a href="http://fsharp.org">F#</a>. This step is by no means required, but it offers another perspective of the translation that you have to perform. According to the <a href="http://blog.ploeh.dk/2017/08/07/f-free-monad-recipe">F# free monad recipe</a>, you can represent the <code>IReservationsRepository</code> interface with a sum type that describes the instruction set of the API: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;ReservationsInstruction&lt;&#39;a&gt;&nbsp;= |&nbsp;IsReservationInFuture&nbsp;<span style="color:blue;">of</span>&nbsp;(Reservation&nbsp;*&nbsp;(bool&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;&#39;a)) |&nbsp;ReadReservations&nbsp;<span style="color:blue;">of</span>&nbsp;(DateTimeOffset&nbsp;*&nbsp;(Reservation&nbsp;list&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;&#39;a)) |&nbsp;Create&nbsp;<span style="color:blue;">of</span>&nbsp;(Reservation&nbsp;*&nbsp;(int&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;&#39;a))</pre> </p> <p> Each case corresponds to a method from the original interface, and each contains a tuple. The first element of the tuple should contain the input to the method, so the first element of <code>IsReservationInFuture</code> is a <code>Reservation</code> value, the first element of <code>ReadReservations</code> is a <code>DateTimeOffset</code>, and the first element of <code>Create</code> is a <code>Reservation</code>, just like <code>IsReservationInFuture</code>. </p> <p> The second tuple element is a <em>continuation</em>. This is a function an interpreter must call once it's produced the value required to continue. This corresponds to the output value from the interface methods, so the input to the continuation associated with <code>IsReservationInFuture</code> is a Boolean value, and so on. </p> <p> The rest of the F# code example follows the recipe to the letter, so it's not important to list it here. You're welcome to look in the Git repository, if you'd like to see the details. </p> <h3 id="82ab72621421406f8c75a9fdb40effb9"> Church-encoded instruction set <a href="#82ab72621421406f8c75a9fdb40effb9" title="permalink">#</a> </h3> <p> From <a href="http://blog.ploeh.dk/2018/05/22/church-encoding">Church encodings</a> we know that we can represent a sum type as an interface with a single <code>Match</code> method. The instruction set is a <a href="http://blog.ploeh.dk/2018/03/22/functors">functor</a>, so it has a generic type argument: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">T</span>&gt;</pre> </p> <p> The <code>Match</code> method must take an argument for each case in the sum type. In the above F# code, you can see that there's three cases, corresponding to the three methods in the original <code>IReservationsRepository</code> interface. </p> <p> Furthermore, we know from the previous articles on Church encodings that the <code>Match</code> method must be generic, and return a value of its generic type argument: </p> <p> <pre><span style="color:#2b91af;">TResult</span>&nbsp;Match&lt;<span style="color:#2b91af;">TResult</span>&gt;(</pre> </p> <p> Third, each argument (i.e. each case from the sum type you're encoding) must have this form: </p> <p> <pre><span style="color:#2b91af;">Func</span>&lt;<em>something</em>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;<em>name</em>,</pre> </p> <p> where <em>something</em> is the type of the data associated with the case, and <em>name</em> is the name of the case. </p> <p> The names are easy: they're <code>isReservationInFuture</code>, <code>readReservations</code>, and <code>create</code>, but what are the types associated with each case? </p> <p> The F# free monad recipe gives the answer, which is why I chose to include the above F# code. For instance, the type associated with the <code>IsReservationInFuture</code> case is <code>Reservation * (bool -&gt; 'a)</code>. That's a tuple, where the first element is a <code>Reservation</code> 'object', and the second element is a function. </p> <p> Take it slow for the first case, then. A tuple where the first element is a <code>Reservation</code> has the type: </p> <p> <pre><span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">Reservation</span>,&nbsp;<em>function-type</em>&gt;</pre> </p> <p> where <em>function-type</em> is the type of the continuation function. In F#, that type was <code>bool -&gt; 'a</code>, which means a function that takes a <code>bool</code> as input, and returns a value of the generic type <code>'a</code> as output. In our Church-encoded C# code, we call that type <code>T</code>, so you need a function from <code>bool</code> to <code>T</code>; that is: <code>Func&lt;bool, T&gt;</code>. If you plug that into the above tuple type, you get: </p> <p> <pre><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;">T</span>&gt;&gt;</pre> </p> <p> Again, you can plug that type into the <em>something</em> place-holder further up, to find the type of the input argument that corresponds to the <code>isReservationInFuture</code> case: </p> <p> <pre><span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;isReservationInFuture</pre> </p> <p> Doing this for the two other cases finally reveals the entire <code>Match</code> method: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Match&lt;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;isReservationInFuture, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;readReservations, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;create); }</pre> </p> <p> That's a worthy candidate for the <em>Ugliest C# method signature of 2018</em> award, I admit, but it's just an intermediate step. This is how the sausage is made. </p> <h3 id="88b4babfff654ff2898165e2a1a635f7"> Implementations of the instruction set <a href="#88b4babfff654ff2898165e2a1a635f7" title="permalink">#</a> </h3> <p> The <code>IReservationsInstruction&lt;T&gt;</code> interface defines an API. You'll need classes that implement the interface in order to do something useful. As you've seen multiple times in the articles series about Church encodings, you must add an implementation per case. Starting from the top: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">IsReservationInFuture</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;:&nbsp;<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</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;">T</span>&gt;&gt;&nbsp;t; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;IsReservationInFuture(<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;">T</span>&gt;&gt;&nbsp;t) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.t&nbsp;=&nbsp;t; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Match&lt;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;isReservationInFuture, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;readReservations, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;create) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;isReservationInFuture(<span style="color:blue;">this</span>.t); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> This class simply <a href="https://en.wikipedia.org/wiki/Adapter_pattern">adapts</a> an 'object' of the type <code>Tuple&lt;Reservation, Func&lt;bool, T&gt;&gt;</code> to the <code>IReservationsInstruction&lt;T&gt;</code> interface. Importantly, it unconditionally calls the <code>Match</code> method's <code>isReservationInFuture</code> argument, while ignoring <code>readReservations</code> and <code>create</code>. This is consistent with the previous incarnations of Church-encodings you've seen. It's an automatable process. You implement the two other cases in the same way: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">ReadReservations</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;:&nbsp;<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</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;">T</span>&gt;&gt;&nbsp;t; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;ReadReservations(<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;">T</span>&gt;&gt;&nbsp;t) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.t&nbsp;=&nbsp;t; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Match&lt;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;isReservationInFuture, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;readReservations, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;create) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;readReservations(<span style="color:blue;">this</span>.t); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> and </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Create</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;:&nbsp;<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</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;">T</span>&gt;&gt;&nbsp;t; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Create(<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;">T</span>&gt;&gt;&nbsp;t) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.t&nbsp;=&nbsp;t; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Match&lt;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;isReservationInFuture, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;readReservations,&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;create) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;create(<span style="color:blue;">this</span>.t); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> If you find the class names odd, then that's a fair criticism. I agree that <code>Create</code> isn't the most object-oriented class name. At this point, though, the design is hardly object-oriented, even though the code in use is C#. You can deal with the names later. </p> <h3 id="8e10a1cdd9e54115804e9ce81fa97460"> Functor <a href="#8e10a1cdd9e54115804e9ce81fa97460" title="permalink">#</a> </h3> <p> The <code>IReservationsInstruction&lt;T&gt;</code> interface is generic, and as expected, it's a functor: </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> Yes, this is horrendous. The F# code is neater: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;<span style="color:blue;">private</span>&nbsp;mapI&nbsp;f&nbsp;=&nbsp;<span style="color:blue;">function</span> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;IsReservationInFuture&nbsp;(x,&nbsp;next)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;IsReservationInFuture&nbsp;(x,&nbsp;next&nbsp;&gt;&gt;&nbsp;f) &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;ReadReservations&nbsp;(x,&nbsp;next)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;ReadReservations&nbsp;(x,&nbsp;next&nbsp;&gt;&gt;&nbsp;f) &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;Create&nbsp;(x,&nbsp;next)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;Create&nbsp;(x,&nbsp;next&nbsp;&gt;&gt;&nbsp;f)</pre> </p> <p> Again, this is an intermediary step. Things will get better. </p> <h3 id="0dccb33718a14bf89ff82fddee7dcd6e"> Church-encoded free monad <a href="#0dccb33718a14bf89ff82fddee7dcd6e" title="permalink">#</a> </h3> <p> Since <code>IReservationsInstruction&lt;T&gt;</code> is a functor, you can package it as a free monad. This entails creating a wrapper 'program' type for it. This is another sum type, in F# written like this: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;ReservationsProgram&lt;&#39;a&gt;&nbsp;= |&nbsp;Free&nbsp;<span style="color:blue;">of</span>&nbsp;ReservationsInstruction&lt;ReservationsProgram&lt;&#39;a&gt;&gt; |&nbsp;Pure&nbsp;<span style="color:blue;">of</span>&nbsp;&#39;a</pre> </p> <p> The direct translation to Church-encoded C#, then, is to a <code>Match</code> method with two arguments: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Match&lt;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;,<span style="color:#2b91af;">TResult</span>&gt;&nbsp;free, &nbsp;&nbsp;&nbsp;&nbsp;&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;pure); }</pre> </p> <p> While the <code>free</code> case looks intimidating, you arrive at it through the same automatic process as already described. </p> <p> The <code>pure</code> case is implemented by this trivial class: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Pure</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;:&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Pure(<span style="color:#2b91af;">T</span>&nbsp;x) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.x&nbsp;=&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Match&lt;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;free, &nbsp;&nbsp;&nbsp;&nbsp;&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;pure) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;pure(<span style="color:blue;">this</span>.x); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> The <code>free</code> case is slightly, but not much, more complex: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Free</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;:&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;i; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Free(<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;i) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.i&nbsp;=&nbsp;i; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Match&lt;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;free, &nbsp;&nbsp;&nbsp;&nbsp;&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;pure) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;free(<span style="color:blue;">this</span>.i); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Both of them, true to the plan we're following, call their respective method arguments with the objects that they adapt. </p> <h3 id="9749b5ad53364a97bc3d25e5ac2c3c40"> Monad <a href="#9749b5ad53364a97bc3d25e5ac2c3c40" title="permalink">#</a> </h3> <p> In C#, the typical monadic <em>bind</em> function is idiomatically called <code>SelectMany</code>, and for various reasons, you need two overloads: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;SelectMany&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;">IReservationsProgram</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;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;selector) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;source.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;free:&nbsp;i&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Free</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;(i.Select(p&nbsp;=&gt;&nbsp;p.SelectMany(selector))), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pure:&nbsp;x&nbsp;=&gt;&nbsp;selector(x)); } <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;SelectMany&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">U</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</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;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">U</span>&gt;&gt;&nbsp;k, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">U</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;s) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;source &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.SelectMany(x&nbsp;=&gt;&nbsp;k(x) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.SelectMany(y&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Pure</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;(s(x,&nbsp;y)))); }</pre> </p> <p> The bottom of the two overloads is required by C# if you want to be able to support various query syntax language constructs. The top overload utilises <code>Match</code> to dispatch between <code>pure</code> and <code>free</code>. Again, the <code>pure</code> case is easy, because you simply call <code>selector</code> with <code>x</code>, and return its result. </p> <p> The <code>free</code> case is more complicated. While <code>i.Select</code> is the <code>Select</code> method defined for <code>IReservationsInstruction&lt;T&gt;</code>, <code>p.SelectMany</code> is a recursive call to the method itself. </p> <p> That's a fly in the ointment, as C# doesn't handle recursion as well as F# or <a href="https://www.haskell.org">Haskell</a>. It'll work fine as long as you don't blow the stack by producing huge programs that have to be interpreted. </p> <h3 id="6f5a47967f9346fcba8d571826bd3f18"> Lifts <a href="#6f5a47967f9346fcba8d571826bd3f18" title="permalink">#</a> </h3> <p> Following the free monad recipe, you'll need to lift each of the instruction set cases to the 'program' type. The following are plain helper methods: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:blue;">bool</span>&gt;&nbsp;IsReservationInFuture(<span style="color:#2b91af;">Reservation</span>&nbsp;reservation) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Free</span>&lt;<span style="color:blue;">bool</span>&gt;( &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;">IReservationsProgram</span>&lt;<span style="color:blue;">bool</span>&gt;&gt;( &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;">IReservationsProgram</span>&lt;<span style="color:blue;">bool</span>&gt;&gt;&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;reservation, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;x&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Pure</span>&lt;<span style="color:blue;">bool</span>&gt;(x)))); } <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&gt;&nbsp;ReadReservations( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;date) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Free</span>&lt;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&gt;( &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;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&gt;&gt;( &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;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&gt;&gt;&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;date, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;x&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Pure</span>&lt;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&gt;(x)))); } <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;Create(<span style="color:#2b91af;">Reservation</span>&nbsp;reservation) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Free</span>&lt;<span style="color:blue;">int</span>&gt;( &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;">IReservationsProgram</span>&lt;<span style="color:blue;">int</span>&gt;&gt;( &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;">IReservationsProgram</span>&lt;<span style="color:blue;">int</span>&gt;&gt;&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;reservation, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;x&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Pure</span>&lt;<span style="color:blue;">int</span>&gt;(x)))); }</pre> </p> <p> Again, the (unfortunately required) type information makes this unreadable, but in fact, not much happens. In F#, the same lift functions are three one-liners: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;isReservationInFuture&nbsp;r&nbsp;=&nbsp;Free&nbsp;(IsReservationInFuture&nbsp;(r,&nbsp;Pure)) <span style="color:blue;">let</span>&nbsp;readReservations&nbsp;d&nbsp;=&nbsp;Free&nbsp;(ReadReservations&nbsp;(d,&nbsp;Pure)) <span style="color:blue;">let</span>&nbsp;create&nbsp;r&nbsp;=&nbsp;Free&nbsp;(Create&nbsp;(r,&nbsp;Pure))</pre> </p> <p> These helper methods serve the sole purpose of making it easier to write client code that produces <code>IReservationsProgram&lt;T&gt;</code> 'objects' (they're actually abstract syntax trees). </p> <h3 id="9bf8fc640105499b80ff9a8a469892fc"> MaîtreD <a href="#9bf8fc640105499b80ff9a8a469892fc" title="permalink">#</a> </h3> <p> You now have all the building blocks that enable you to refactor <code>MaîtreD.TryAccept</code> to return an <code>IReservationsProgram&lt;int?&gt;</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">MaîtreD</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IMaîtreD</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;MaîtreD(<span style="color:blue;">int</span>&nbsp;capacity) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Capacity&nbsp;=&nbsp;capacity; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:blue;">int</span>?&gt;&nbsp;TryAccept(<span style="color:#2b91af;">Reservation</span>&nbsp;reservation) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">ReservationsProgram</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.IsReservationInFuture(reservation) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.SelectMany(isInFuture&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!isInFuture) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Pure</span>&lt;<span style="color:blue;">int</span>?&gt;(<span style="color:blue;">null</span>); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">ReservationsProgram</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.ReadReservations(reservation.Date) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.SelectMany(reservations&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;reservedSeats&nbsp;=&nbsp;reservations.Sum(r&nbsp;=&gt;&nbsp;r.Quantity); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(Capacity&nbsp;&lt;&nbsp;reservedSeats&nbsp;+&nbsp;reservation.Quantity) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Pure</span>&lt;<span style="color:blue;">int</span>?&gt;(<span style="color:blue;">null</span>); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;reservation.IsAccepted&nbsp;=&nbsp;<span style="color:blue;">true</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">ReservationsProgram</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Create(reservation) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Select(x&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:blue;">int</span>?(x)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">int</span>&nbsp;Capacity&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} }</pre> </p> <p> This is hardly as pretty as the original version that used Dependency Injection, but you should notice an interesting effect: by returning a free monad, you get rid of the injected dependency. While the code still depends on <code>Capacity</code>, that's just a read-only number. </p> <p> Through the so-called <em>query syntax</em>, C# offers some syntactic sugar for monadic composition, similar to F#'s <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/computation-expressions">computation expressions</a> or Haskell's <code>do</code> notation. Where its utility ends, though, is exactly where you need it. Unfortunately, it doesn't support branching (the use of <code>if</code> statements and such) inside of <code>from x in xs</code> expressions, so while we've supplied the requisite <code>SelectMany</code> methods for <code>IReservationsProgram&lt;T&gt;</code>, you can't use them. </p> <p> Instead, you have to resort to branching inside of each continuation, which, unfortunately, pulls you towards <a href="http://wiki.c2.com/?ArrowAntiPattern">arrow code</a>. </p> <p> The <code>TryAccept</code> method starts by calling the <code>IsReservationInFuture</code> helper method (defined above), which returns an <code>IReservationsProgram&lt;bool&gt;</code> object. You can't easily pull the <code>bool</code> value out of the container, but you can use <code>SelectMany</code> to define what happens next. </p> <p> If the reservations is in the future, an interpreter should call the continuation with <code>true</code>, and otherwise, with <code>false</code>. Thus, you can branch on that Boolean value for the next step. If the reservations turned out to be in the past, the return value ought to be <code>null</code>, but you have to package that in an <code>IReservationsProgram&lt;int?&gt;</code>. The correct way to do that is to wrap it in a <code>Pure</code> object. </p> <p> If the reservation, on the other hand, turned out to be in the future, the program can continue. It proceeds to call the <code>ReadReservations</code> helper method, and again uses <code>SelectMany</code> to define what happens next. An interpreter will supply <code>reservations</code> (presumably read from an actual database), and the code inside the continuation decides what to do next. In the case of insufficient remaining capacity, you return another <code>null</code> wrapped in <code>Pure</code>, but if you decide to accept the reservation, you can finally call the <code>Create</code> helper method and return its return value. Here, however, C#'s implicit conversion no longer works, so you have to explicitly use <code>Select</code> to turn the <code>int</code> into an <code>int?</code>. </p> <h3 id="049e04b81e2f4e3ba39d40f4275038a5"> Interpreters <a href="#049e04b81e2f4e3ba39d40f4275038a5" title="permalink">#</a> </h3> <p> You can still unit test the code by supplying a test-specific interpreter, but in the interest of keeping this article to essentials, I'll refer you to the code repository if you want to see how the tests look at this point. </p> <p> You're probably more interested in seeing how an interpreter actually interacts with a real database, like the above <code>SqlReservationsRepository</code> class did. The scenario is still the same, only the specifics have changed. Instead of implementing an interface, you'll now have to interpret an <code>IReservationsProgram&lt;int?&gt;</code>. How do you do that? </p> <p> You do it like you'd traverse any other Church-encoded sum type: use the <code>Match</code> method and supply a handler for each of the cases: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Interpret&lt;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;program, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;connectionString) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;program.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pure:&nbsp;x&nbsp;=&gt;&nbsp;x, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;free:&nbsp;i&nbsp;=&gt;&nbsp;i.Match( &nbsp;&nbsp;&nbsp;&nbsp;&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;&nbsp;&nbsp;&nbsp;&nbsp;t.Item2(IsReservationInFuture(t.Item1)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Interpret(connectionString), &nbsp;&nbsp;&nbsp;&nbsp;&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;&nbsp;&nbsp;&nbsp;&nbsp;t.Item2(ReadReservations(t.Item1,&nbsp;connectionString)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Interpret(connectionString), &nbsp;&nbsp;&nbsp;&nbsp;&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;&nbsp;&nbsp;&nbsp;&nbsp;t.Item2(Create(t.Item1,&nbsp;connectionString)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Interpret(connectionString))); }</pre> </p> <p> Since a free monad is a nested, recursive sum type, you'll first have to supply handlers for the <code>pure</code> and <code>free</code> cases. The <code>pure</code> case is, as always, trivial. This is where you finally encounter a leaf node in the abstract syntax tree you're traversing. This is where you get to return the final value of the program. </p> <p> In the <code>free</code> case, on the other hand, you'll need to handle an <code>IReservationsInstruction&lt;IReservationsProgram&lt;T&gt;&gt;</code> value, which is another Church-encoded sum type. It looks daunting, but is an entirely automatic refactoring: just call <code>Match</code> on that object as well, and supply a handler for each of the cases. </p> <p> Recall that each of the cases of <code>IReservationsInstruction&lt;T&gt;</code> contains a tuple. The first element (<code>t.Item1</code>) is a value to be used as an input argument for the interpreter. The second element (<code>t.Item2</code>) is a function. Notice that in all three cases, this interpreter calls a helper method with <code>t.Item1</code> and then calls the continuation <code>t.Item2</code> with the return value from the helper method; e.g. <code>t.Item2(IsReservationInFuture(t.Item1))</code>. All three continuation functions return a new <code>IReservationsProgram&lt;T&gt;</code>, representing the next step in the program, so you'll have to recursively call <code>Interpret</code> again. </p> <p> The <code>IsReservationInFuture</code> helper method is simple: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;IsReservationInFuture(<span style="color:#2b91af;">Reservation</span>&nbsp;reservation) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>.Now&nbsp;&lt;&nbsp;reservation.Date; }</pre> </p> <p> Notice that this is an entirely normal static helper method that every C# programmer should know how to write. You're now back on familiar territory. The same goes for the two other helper methods <code>ReadReservations</code> and <code>Create</code>. They're slightly refactored versions of the above <code>SqlReservationsRepository</code> methods, so I'm not going to repeat them here. Again, you're welcome to look at the details in the code repository. </p> <h3 id="4ec6be3a82684d77933b98c6dc625b94"> Refactor instruction arguments to Parameter Object <a href="#4ec6be3a82684d77933b98c6dc625b94" title="permalink">#</a> </h3> <p> As you know from another article, <a href="http://blog.ploeh.dk/2018/06/25/visitor-as-a-sum-type">you can refactor any Church-encoded sum type to a Visitor</a>. If you want to do it step-wise, you start by introducing a Parameter Object, as suggested by <a href="http://amzn.to/YPdQDf">Refactoring</a>. There's two sum types in play in this code base, but you can arbitrarily choose to start with the instruction set. Instead of taking three method arguments, change the <code>Match</code> method so that it takes only a single argument: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Match&lt;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">ReservationsInstructionParameters</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;parameters); }</pre> </p> <p> The new Parameter Object looks like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">ReservationsInstructionParameters</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;ReservationsInstructionParameters( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;isReservationInFuture, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;readReservations, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;create) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.IsReservationInFuture&nbsp;=&nbsp;isReservationInFuture; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.ReadReservations&nbsp;=&nbsp;readReservations; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.Create&nbsp;=&nbsp;create; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;IsReservationInFuture&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ReadReservations&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Func</span>&lt;<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;">T</span>&gt;&gt;,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;Create&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} }</pre> </p> <p> This change clearly just moves things around, so nothing much is yet gained. You'll need to adjust other parts of the code in order to pass an instance of this Parameter Object to the <code>Match</code> method, but that's trivial and automatable work, so I'll skip showing it. </p> <p> If you've noticed that the <code>ReservationsInstructionParameters&lt;T, TResult&gt;</code> Parameter Object is nothing but a container of three functions, you may not be impressed, but from <a href="http://blog.ploeh.dk/2018/02/12/object-isomorphisms">Object isomorphisms</a> we know that a tuple (or record) of functions is isomorphic to an object, thereby nicely putting everything in place for the next change. </p> <h3 id="9adbd66ce0874681b5a47d27d29770e2"> Refactor instruction set Parameter Object to an interface <a href="#9adbd66ce0874681b5a47d27d29770e2" title="permalink">#</a> </h3> <p> Instead of a record of three functions, refactor the Parameter Object to an interface with three members: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IReservationsInstructionParameters</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;IsReservationInFuture(<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;">T</span>&gt;&gt;&nbsp;t); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;ReadReservations(<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;">T</span>&gt;&gt;&nbsp;t); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Create(<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;">T</span>&gt;&gt;&nbsp;t); }</pre> </p> <p> Each function is now a method on the interface. Still not perfect, but better. Again, you have to make all sort of adjustments to code that interacts with the <code>Match</code> method. This is the most laborious refactoring, because in every place where before you could simply pass lambda expressions, you now have to introduce explicit classes that implement the interface. </p> <p> For example, the database interpreter now has to look like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Interpret&lt;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;program, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;connectionString) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;program.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pure:&nbsp;x&nbsp;=&gt;&nbsp;x, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;free:&nbsp;i&nbsp;=&gt;&nbsp;i.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">InterpretReservationsInstructionParameters</span>&lt;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;connectionString))); }</pre> </p> <p> So far, we've only started refactoring the instruction set, so you still need to handle <code>IReservationsProgram&lt;T&gt;</code> values by supplying two lambda expressions to its <code>Match</code> method. When handling the instruction <code>i</code>, however, you must now supply an implementation of the new <code>IReservationsInstructionParameters&lt;T, TResult&gt;</code> interface. </p> <p> You can do that by creating a new private, nested class: </p> <p> <pre><span style="color:blue;">private</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">InterpretReservationsInstructionParameters</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;: &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IReservationsInstructionParameters</span>&lt;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;,&nbsp;<span style="color:#2b91af;">T</span>&gt;</pre> </p> <p> As an example, this class implements the <code>ReadReservations</code> method like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;ReadReservations( &nbsp;&nbsp;&nbsp;&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;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&gt;&nbsp;t) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;reservations&nbsp;=&nbsp;ReadReservations( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.Item1.Date, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.Item1.Date.AddDays(1).AddTicks(-1)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;t.Item2(reservations).Interpret(connectionString); } <span style="color:blue;">private</span>&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&nbsp;ReadReservations( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;min, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;max)</pre> </p> <p> The method first calls a helper method also called <code>ReadReservations</code> to read the reservations from the database. That helper method is a perfectly normal C# method that queries a database. Its implementation is equivalent to the above <code>SqlReservationsRepository.ReadReservations</code> implementation, so while I've included its signature in the above code listing, there's no need to repeat the method body here. </p> <p> Keep in mind that <code>t</code> is the horribly typed tuple declared as the method argument, so <code>t.Item1</code> is just a <code>DateTimeOffset</code> value that you can pass as argument(s) to the <code>ReadReservations</code> helper method. </p> <p> The helper method returns <code>reservations</code>, which is an <code>IReadOnlyCollection&lt;Reservation&gt;</code>. You can now (as before) call the continuation function <code>t.Item2</code> with that object. The continuation returns a new <code>IReservationsProgram&lt;T&gt;</code> that you'll then have to recursively handle by calling <code>Interpret</code> again. This is just like before the refactoring. </p> <h3 id="6a6b11b4983942fea7a6125a95e6adcd"> Rename instruction set API <a href="#6a6b11b4983942fea7a6125a95e6adcd" title="permalink">#</a> </h3> <p> You're simply following the refactoring steps outlined in <a href="http://blog.ploeh.dk/2018/06/25/visitor-as-a-sum-type">Visitor as a sum type</a>, so now you can rename the types involved with the instruction set to follow the naming conventions of the Visitor design pattern: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IReservationsInstructionVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;VisitIsReservationInFuture(<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;">T</span>&gt;&gt;&nbsp;t); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;VisitReadReservations(<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;">T</span>&gt;&gt;&nbsp;t); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;VisitCreate(<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;">T</span>&gt;&gt;&nbsp;t); }</pre> </p> <p> This is the interface previously named <code>IReservationsInstructionParameters&lt;T, TResult&gt;</code> renamed, and with the word <code>Visit</code> affixed. Likewise, you can also make similar changes to the <code>IReservationsInstruction&lt;T&gt;</code> interface: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Accept&lt;<span style="color:#2b91af;">TResult</span>&gt;(<span style="color:#2b91af;">IReservationsInstructionVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;visitor); }</pre> </p> <p> These changes are simple rename refactorings, so while they affect much other code, I'm not going to list it all. </p> <h3 id="737d486102ea48e286e4fca81d7ea3f8"> Make program API a Visitor <a href="#737d486102ea48e286e4fca81d7ea3f8" title="permalink">#</a> </h3> <p> Following the same refactoring steps, you can also turn <code>IReservationsProgram&lt;T&gt;</code> into an application of the Visitor design pattern: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;Accept&lt;<span style="color:#2b91af;">TResult</span>&gt;(<span style="color:#2b91af;">IReservationsProgramVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;visitor); }</pre> </p> <p> You simply rename the <code>Match</code> method to <code>Accept</code>, and call the object passed to it <code>visitor</code>. The Visitor itself is defined like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IReservationsProgramVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;VisitFree(<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;i); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;VisitPure(<span style="color:#2b91af;">T</span>&nbsp;x); }</pre> </p> <p> While these steps conclude the refactoring steps outlined in the previously mentioned article on how to turn a Church-encoded sum type into a Visitor, the resulting code can still benefit from further clean-up. </p> <h3 id="b362e6cd50dc4f1f855fa83790250997"> Refactor tuple argument to argument list <a href="#b362e6cd50dc4f1f855fa83790250997" title="permalink">#</a> </h3> <p> If you consider the current definition of <code>IReservationsInstructionVisitor&lt;T, TResult&gt;</code> (see above), you'll notice that each method takes a single argument in the shape of a tuple. From <a href="http://blog.ploeh.dk/2018/01/29/argument-list-isomorphisms">Argument list isomorphisms</a> you know that you can refactor such a method into a method that takes a normal argument list: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IReservationsInstructionVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;VisitIsReservationInFuture( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Reservation</span>&nbsp;reservation, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">bool</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;continuation); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;VisitReadReservations( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;date, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&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;">T</span>&gt;&nbsp;continuation); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">TResult</span>&nbsp;VisitCreate( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Reservation</span>&nbsp;reservation, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;continuation); }</pre> </p> <p> Each of these methods now take an input argument (e.g. a <code>Reservation</code> or a <code>DateTimeOffset</code>) and a continuation function. This already improves the API. </p> <h3 id="824a28cae0224aaf89332305889034f6"> SQL Visitor <a href="#824a28cae0224aaf89332305889034f6" title="permalink">#</a> </h3> <p> In an attempt to make things look proper object-oriented, then, the journey is complete. Instead of a <code>SqlReservationsRepository</code>, you instead need a <code>SqlReservationsProgramVisitor&lt;T&gt;</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">SqlReservationsProgramVisitor</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;: &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IReservationsProgramVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IReservationsInstructionVisitor</span>&lt;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;,&nbsp;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:blue;">string</span>&nbsp;connectionString; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;SqlReservationsProgramVisitor(<span style="color:blue;">string</span>&nbsp;connectionString) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.connectionString&nbsp;=&nbsp;connectionString; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;VisitPure(<span style="color:#2b91af;">T</span>&nbsp;x) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;VisitFree(<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;i) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;i.Accept(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;VisitIsReservationInFuture( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Reservation</span>&nbsp;reservation, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">bool</span>,&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;continuation) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;isInFuture&nbsp;=&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>.Now&nbsp;&lt;&nbsp;reservation.Date; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;continuation(isInFuture).Accept(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;VisitReadReservations( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;date, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&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;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;continuation) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;reservations&nbsp;=&nbsp;ReadReservations( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;date.Date, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;date.Date.AddDays(1).AddTicks(-1)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;continuation(reservations).Accept(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&nbsp;ReadReservations( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;min, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;max) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;result&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">using</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;conn&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SqlConnection</span>(connectionString)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">using</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;cmd&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SqlCommand</span>(readByRangeSql,&nbsp;conn)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cmd.Parameters.Add(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SqlParameter</span>(<span style="color:#a31515;">&quot;@MinDate&quot;</span>,&nbsp;min)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cmd.Parameters.Add(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SqlParameter</span>(<span style="color:#a31515;">&quot;@MaxDate&quot;</span>,&nbsp;max)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;conn.Open(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">using</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;rdr&nbsp;=&nbsp;cmd.ExecuteReader()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">while</span>&nbsp;(rdr.Read()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.Add( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&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;">Reservation</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date&nbsp;=&nbsp;(<span style="color:#2b91af;">DateTimeOffset</span>)rdr[<span style="color:#a31515;">&quot;Date&quot;</span>], &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;(<span style="color:blue;">string</span>)rdr[<span style="color:#a31515;">&quot;Name&quot;</span>], &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Email&nbsp;=&nbsp;(<span style="color:blue;">string</span>)rdr[<span style="color:#a31515;">&quot;Email&quot;</span>], &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Quantity&nbsp;=&nbsp;(<span style="color:blue;">int</span>)rdr[<span style="color:#a31515;">&quot;Quantity&quot;</span>] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;result; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">const</span>&nbsp;<span style="color:blue;">string</span>&nbsp;readByRangeSql&nbsp;=&nbsp;<span style="color:maroon;">@&quot; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;SELECT&nbsp;[Date],&nbsp;[Name],&nbsp;[Email],&nbsp;[Quantity] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;FROM&nbsp;[dbo].[Reservations] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WHERE&nbsp;YEAR(@MinDate)&nbsp;&lt;=&nbsp;YEAR([Date]) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AND&nbsp;MONTH(@MinDate)&nbsp;&lt;=&nbsp;MONTH([Date]) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AND&nbsp;DAY(@MinDate)&nbsp;&lt;=&nbsp;DAY([Date]) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AND&nbsp;YEAR([Date])&nbsp;&lt;=&nbsp;YEAR(@MaxDate) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AND&nbsp;MONTH([Date])&nbsp;&lt;=&nbsp;MONTH(@MaxDate) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AND&nbsp;DAY([Date])&nbsp;&lt;=&nbsp;DAY(@MaxDate)&quot;</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;VisitCreate( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Reservation</span>&nbsp;reservation, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;continuation) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;continuation(Create(reservation)).Accept(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">int</span>&nbsp;Create(<span style="color:#2b91af;">Reservation</span>&nbsp;reservation) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">using</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;conn&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SqlConnection</span>(connectionString)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">using</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;cmd&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SqlCommand</span>(createReservationSql,&nbsp;conn)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cmd.Parameters.Add( &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;">SqlParameter</span>(<span style="color:#a31515;">&quot;@Date&quot;</span>,&nbsp;reservation.Date)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cmd.Parameters.Add( &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;">SqlParameter</span>(<span style="color:#a31515;">&quot;@Name&quot;</span>,&nbsp;reservation.Name)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cmd.Parameters.Add( &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;">SqlParameter</span>(<span style="color:#a31515;">&quot;@Email&quot;</span>,&nbsp;reservation.Email)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cmd.Parameters.Add( &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;">SqlParameter</span>(<span style="color:#a31515;">&quot;@Quantity&quot;</span>,&nbsp;reservation.Quantity)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;conn.Open(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;cmd.ExecuteNonQuery(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">const</span>&nbsp;<span style="color:blue;">string</span>&nbsp;createReservationSql&nbsp;=&nbsp;<span style="color:maroon;">@&quot; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;INSERT&nbsp;INTO&nbsp;[dbo].[Reservations]&nbsp;([Date],&nbsp;[Name],&nbsp;[Email],&nbsp;[Quantity]) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;VALUES&nbsp;(@Date,&nbsp;@Name,&nbsp;@Email,&nbsp;@Quantity)&quot;</span>; }</pre> </p> <p> Most of this code is similar to the <code>SqlReservationsRepository</code> from the beginning of the article. The <code>IReservationsRepository</code> interface no longer exists; instead this Visitor implements two interfaces: <code>IReservationsProgramVisitor&lt;T, T&gt;</code> and <code>IReservationsInstructionVisitor&lt;IReservationsProgram&lt;T&gt;, T&gt;</code>. A free monad recursively interacts with itself by going back and forth between an 'instruction' and the overall 'program'. Implementing both interfaces in a single class makes it much easier to transition between these two views, as you no longer have to pass e.g. the <code>connectionString</code> around between various objects. </p> <p> This also means that instead of having to rely on an extension method in order to be able to continue, notice that each method can now continue by calling <code>Accept(this)</code>. </p> <p> Instead of injecting <code>IReservationsRepository</code> into objects, you can call methods that return <code>IReservationsProgram&lt;T&gt;</code> objects and then interpret them using the above <code>SqlReservationsProgramVisitor&lt;T&gt;</code>. For example, you could call <code>TryAccept</code> with a <code>Reservation</code> object: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;p&nbsp;=&nbsp;maîtreD.TryAccept(reservation);</pre> </p> <p> The <code>p</code> variable is an <code>IReservationsProgram&lt;int?&gt;</code> object, where the <code>int?</code> represents a potential reservation ID. At this point, <code>p</code> is a 'program', and you can 'run' it by asking it to accept a Visitor: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;id&nbsp;=&nbsp;p.Accept(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SqlReservationsProgramVisitor</span>&lt;<span style="color:blue;">int</span>?&gt;(connectionString)); </pre> </p> <p> When <code>Accept</code> returns, <code>id</code> (an <code>int?</code>) has a value, or is <code>null</code>, according to the exact details of <code>reservation</code> and the state of the database. </p> <h3 id="4cf204a182af44ea8145e16915752e89"> Testability <a href="#4cf204a182af44ea8145e16915752e89" title="permalink">#</a> </h3> <p> Is this design still testable? Yes, indeed, the overall free monad design is <a href="https://en.wikipedia.org/wiki/Pure_function">pure</a>, and thereby <a href="http://blog.ploeh.dk/2015/05/07/functional-design-is-intrinsically-testable">inherently testable</a>. Instead of using a dynamic mock library like Moq, you can add a test-specific implementation of the free monad Visitor to your unit testing code base: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">StubReservationsVisitor</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;: &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IReservationsProgramVisitor</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IReservationsInstructionVisitor</span>&lt;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;,&nbsp;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;isInFuture; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&nbsp;reservations; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:blue;">int</span>&nbsp;id; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;StubReservationsVisitor( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">bool</span>&nbsp;isInFuture, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&nbsp;reservations, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;id) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.isInFuture&nbsp;=&nbsp;isInFuture; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.reservations&nbsp;=&nbsp;reservations; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.id&nbsp;=&nbsp;id; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;VisitPure(<span style="color:#2b91af;">T</span>&nbsp;x) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;VisitFree(<span style="color:#2b91af;">IReservationsInstruction</span>&lt;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;i) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;i.Accept(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;VisitIsReservationInFuture( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Reservation</span>&nbsp;reservation, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">bool</span>,&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;continuation) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;continuation(isInFuture).Accept(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;VisitReadReservations( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;date, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&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;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;continuation) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;continuation(reservations).Accept(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;VisitCreate( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Reservation</span>&nbsp;reservation, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:#2b91af;">IReservationsProgram</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;continuation) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;continuation(id).Accept(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> As a true <a href="http://xunitpatterns.com/Test%20Stub.html">Stub</a>, this implementation ignores the input values and returns pre-configured values. When <code>VisitIsReservationInFuture</code> is called, for example, the implementation ignores the <code>reservation</code> argument and instead 'returns' the <code>isInFuture</code> class field by calling <code>continuation(isInFuture)</code>. </p> <p> You can exercise the happy-path test case from the beginning of this article as a unit test using this Stub Visitor: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">BookingApiTestConventions</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;TryAcceptReturnsReservationIdInHappyPathScenario( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Reservation</span>&nbsp;reservation, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Reservation</span>&gt;&nbsp;reservations, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">MaîtreD</span>&nbsp;sut, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;excessCapacity, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;expected) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;reservedSeats&nbsp;=&nbsp;reservations.Sum(r&nbsp;=&gt;&nbsp;r.Quantity); &nbsp;&nbsp;&nbsp;&nbsp;reservation.IsAccepted&nbsp;=&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;sut&nbsp;=&nbsp;sut.WithCapacity( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;reservedSeats&nbsp;+&nbsp;reservation.Quantity&nbsp;+&nbsp;excessCapacity); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;sut.TryAccept(reservation); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;expected, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;actual.Accept(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">StubReservationsVisitor</span>&lt;<span style="color:blue;">int</span>?&gt;(<span style="color:blue;">true</span>,&nbsp;reservations,&nbsp;expected))); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.True(reservation.IsAccepted); }</pre> </p> <p> This test still uses AutoFixture to create objects such as <code>reservation</code>, <code>reservations</code>, and so on, but instead of relying on dynamic mocks injected into the <code>sut</code>, it uses the <code>StubReservationsVisitor&lt;T&gt;</code> class to interpret the return value from <code>TryAccept</code>. </p> <h3 id="fa5ef38abcb84dee913b517ebcd2bfb5"> Arrow code <a href="#fa5ef38abcb84dee913b517ebcd2bfb5" title="permalink">#</a> </h3> <p> From an external perspective, as a user of <code>MaîtreD.TryAccept</code>, the API looks exotic, but to a degree, fairly object-oriented, with its implementation of the Visitor design pattern. Looking at the above internal implementation of the method, however, reveals the most problematic part of this entire exercise. The code doesn't look nice. </p> <p> Not only do we have nested closures, but it also looks like the dreaded Arrow Code anti-pattern. Partially, the problem is that while C# has some support for monadic syntactic sugar, in the form of query expressions, you can't branch inside a query expression. That's not the whole problem, though. Even in F#, with a computation expression, the equivalent code would look like this: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;tryAccept&nbsp;capacity&nbsp;reservation&nbsp;=&nbsp;reservations&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;isInFuture&nbsp;=&nbsp;isReservationInFuture&nbsp;reservation &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;not&nbsp;isInFuture &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">then</span>&nbsp;<span style="color:blue;">return</span>&nbsp;None &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">else</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;reservations&nbsp;=&nbsp;readReservations&nbsp;reservation.Date &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;reservedSeats&nbsp;=&nbsp;List.sumBy&nbsp;(<span style="color:blue;">fun</span>&nbsp;r&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;r.Quantity)&nbsp;reservations &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(capacity&nbsp;&lt;&nbsp;reservedSeats&nbsp;+&nbsp;reservation.Quantity) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">then</span>&nbsp;<span style="color:blue;">return</span>&nbsp;None &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">else</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;reservationId&nbsp;=&nbsp;create&nbsp;{&nbsp;reservation&nbsp;<span style="color:blue;">with</span>&nbsp;IsAccepted&nbsp;=&nbsp;<span style="color:blue;">true</span>&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;Some&nbsp;reservationId&nbsp;}</pre> </p> <p> While this looks smoother, the code still exhibits the arrow shape. There are ways to address that problem, but that's a topic for the next article. </p> <h3 id="a1d12d37f6de436cbe2a966eb12f4bc9"> Conclusion <a href="#a1d12d37f6de436cbe2a966eb12f4bc9" title="permalink">#</a> </h3> <p> Even in C#, you can refactor from Dependency Injection to a free monad, implemented as a Visitor. Should you, though? </p> <p> As a rule of thumb, no, I don't think it's a good idea. Free monads are worth considering in Haskell where they are much closer to being 'free', in the sense that there's little programming overhead involved with defining and using them. Already when you translate a free monad to F# do you discover how much boilerplate programming is involved. Still, due to F#'s computation expressions, a free monad may occasionally be worth considering. Both in implementation and at call sites, you can make the API easy to use. </p> <p> In C#, you run into its lack of support for branching inside monadic composition. Not only does a free monad look <a href="http://blog.ploeh.dk/2015/08/03/idiomatic-or-idiosyncratic">non-idiomatic</a> in C#, but writing the 'programs' without good syntactic sugar for monads make this alternative even less compelling. To make matters worse, the boilerplate code you have to write in C# is positively ugly. As this article is a result of an experiment, I admit that I have no production experience with free monads as Visitors in C#. Still, due to the lack of type inference in crucial parts, I'd venture the guess that the implementation would also prove to be frustratingly refactor-resistant. </p> <p> Perhaps, one day, you'll run into an edge case where you have a dependency that could benefit from being refactored to a Visitor, but in general, I'd presume that Dependency Injection in C# is the lesser of two evils. Still, I think it's interesting, and illustrative, that it's possible to refactor an injected dependency to a free monad - even in C#! </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/07/30/flattening-arrow-code-using-a-stack-of-monads">Flattening arrow code using a stack of monads</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Angular addition monoid http://blog.ploeh.dk/2018/07/16/angular-addition-monoid 2018-07-16T14:40:00+00:00 Mark Seemann <div id="post"> <p> <em>Geometric angles can be added together. Angular addition forms a monoid.</em> </p> <p> This article is part of a <a href="http://blog.ploeh.dk/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>). </p> <p> In geometry, an angle is a measure of how two crossing lines relate to each other. In mathematics, angles are usually represented in radians, but in daily use, they're mostly measured in degrees between 0 and 360. </p> <h3 id="beb83a6d54c6454085e6bf78e381cd9a"> Angular addition <a href="#beb83a6d54c6454085e6bf78e381cd9a" title="permalink">#</a> </h3> <p> You can always draw an angle within a circle. Here's a 45° angle: </p> <p> <img src="/content/binary/angle-45.png" alt="A 45° angle."> </p> <p> If you add another 90° angle to that, you get a 135° angle: </p> <p> <img src="/content/binary/angle-45-90.png" alt="A 45° angle and a 90° angle added to it."> </p> <p> What do you get if you add 90° to 315°? </p> <p> <img src="/content/binary/angle-315-plus-90.png" alt="A 315° angle and a 90° angle next to it."> </p> <p> Well, you get 45°, of course! </p> <p> <img src="/content/binary/angle-315-90.png" alt="A 315° angle and a 90° angle overlaid on the first one."> </p> <p> There's only 360° in a circle, so overflow is handled, in this case, by subtracting 360°. In general, however, angular addition is nothing but modulo 360 addition. </p> <h3 id="53d5cb53bc904c9c8430ed21973fc490"> Angle struct <a href="#53d5cb53bc904c9c8430ed21973fc490" title="permalink">#</a> </h3> <p> You can model a geometric angle as a struct. Here's a simple example: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">struct</span>&nbsp;<span style="color:#2b91af;">Angle</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:blue;">decimal</span>&nbsp;degrees; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;Angle(<span style="color:blue;">decimal</span>&nbsp;degrees) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.degrees&nbsp;=&nbsp;degrees&nbsp;%&nbsp;360m; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(<span style="color:blue;">this</span>.degrees&nbsp;&lt;&nbsp;0) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.degrees&nbsp;+=&nbsp;360m; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Angle</span>&nbsp;FromDegrees(<span style="color:blue;">decimal</span>&nbsp;degrees) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Angle</span>(degrees); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Angle</span>&nbsp;FromRadians(<span style="color:blue;">double</span>&nbsp;radians) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Angle</span>((<span style="color:blue;">decimal</span>)((180D&nbsp;/&nbsp;<span style="color:#2b91af;">Math</span>.PI)&nbsp;*&nbsp;radians)); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Angle</span>&nbsp;Add(<span style="color:#2b91af;">Angle</span>&nbsp;other) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Angle</span>(<span style="color:blue;">this</span>.degrees&nbsp;+&nbsp;other.degrees); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Angle</span>&nbsp;Identity&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Angle</span>(0); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;Equals(<span style="color:blue;">object</span>&nbsp;obj) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(obj&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:#2b91af;">Angle</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;((<span style="color:#2b91af;">Angle</span>)obj).degrees&nbsp;==&nbsp;<span style="color:blue;">this</span>.degrees; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">base</span>.Equals(obj); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">int</span>&nbsp;GetHashCode() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.degrees.GetHashCode(); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;<span style="color:blue;">operator</span>&nbsp;==(<span style="color:#2b91af;">Angle</span>&nbsp;x,&nbsp;<span style="color:#2b91af;">Angle</span>&nbsp;y) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;x.Equals(y); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;<span style="color:blue;">operator</span>&nbsp;!=(<span style="color:#2b91af;">Angle</span>&nbsp;x,&nbsp;<span style="color:#2b91af;">Angle</span>&nbsp;y) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;!x.Equals(y); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Notice the <code>Add</code> method, <a href="http://blog.ploeh.dk/2017/10/06/monoids">which is a binary operation</a>; it's an instance method on <code>Angle</code>, takes another <code>Angle</code> as input, and returns an <code>Angle</code> value. </p> <h3 id="65f48d17d79b4096a8c192ec7675496d"> Associativity <a href="#65f48d17d79b4096a8c192ec7675496d" title="permalink">#</a> </h3> <p> Not only is <code>Add</code> a binary operation; it's also associative. Here's an example: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;x&nbsp;=&nbsp;<span style="color:#2b91af;">Angle</span>.FromDegrees(135); <span style="color:blue;">var</span>&nbsp;y&nbsp;=&nbsp;<span style="color:#2b91af;">Angle</span>.FromDegrees(180); <span style="color:blue;">var</span>&nbsp;z&nbsp;=&nbsp;<span style="color:#2b91af;">Angle</span>.FromDegrees(300); <span style="color:blue;">var</span>&nbsp;left&nbsp;&nbsp;=&nbsp;x.Add(y).Add(z); <span style="color:blue;">var</span>&nbsp;right&nbsp;=&nbsp;x.Add(y.Add(z));</pre> </p> <p> Notice that <code>left</code> first evaluates <code>x.Add(y)</code>, which is 315°; then it adds 300°, which is 615°, but normalises to 255°. On the other hand, <code>right</code> first evaluates <code>y.Add(z)</code>, which is 480°, but normalises to 120°. It then adds those 120° to <code>x</code>, for a final result of 255°. Since <code>left</code> and <code>right</code> are both 255°, this illustrates that <code>Add</code> is associative. </p> <p> Obviously, this is only a single example, so it's no proof. While still not a proof, you can demonstrate the associativity property with more confidence by writing a property-based test. Here's one using <a href="https://fscheck.github.io/FsCheck">FsCheck</a> and <a href="https://xunit.github.io">xUnit.net</a>: </p> <p> <pre>[<span style="color:#2b91af;">Property</span>(QuietOnSuccess&nbsp;=&nbsp;<span style="color:blue;">true</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;AddIsAssociative(<span style="color:#2b91af;">Angle</span>&nbsp;x,&nbsp;<span style="color:#2b91af;">Angle</span>&nbsp;y,&nbsp;<span style="color:#2b91af;">Angle</span>&nbsp;z) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;x.Add(y).Add(z), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;x.Add(y.Add(z))); }</pre> </p> <p> By default, FsCheck generates 100 test cases, but even when I experimentally change the configuration to run 100,000 test cases, they all pass. For full disclosure, however, I'll admit that I defined the data generators to only use <code>NormalFloat</code> for the radian values, and only <code>decimal</code> values with up to 10 decimal places. If you try to use entirely unconstrained floating points, you'll see test failures caused by rounding errors. </p> <p> Changing the data generator is one way to address rounding errors. Another way is to add a bit of fuzzy tolerance to the assertion. In any case, though, the <code>Add</code> operation is associative. That rounding errors occur is an implementation detail of floating point arithmetic. </p> <h3 id="a912f6c80aeb4619b30476e3183edcc9"> Identity <a href="#a912f6c80aeb4619b30476e3183edcc9" title="permalink">#</a> </h3> <p> The above code listing defines a value called <code>Identity</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Angle</span>&nbsp;Identity&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Angle</span>(0);</pre> </p> <p> <em>As an Angle, I want my Add and Identity members to obey the monoid laws so that I can be a monoid.</em> </p> <p> As an example, both <code>left</code> and <code>right</code> should be <code>true</code> in the following: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;x&nbsp;=&nbsp;<span style="color:#2b91af;">Angle</span>.FromDegrees(370); <span style="color:blue;">var</span>&nbsp;left&nbsp;&nbsp;=&nbsp;x&nbsp;==&nbsp;<span style="color:#2b91af;">Angle</span>.Identity.Add(x); <span style="color:blue;">var</span>&nbsp;right&nbsp;=&nbsp;x&nbsp;==&nbsp;x.Add(<span style="color:#2b91af;">Angle</span>.Identity);</pre> </p> <p> That does, indeed, turn out to be the case. </p> <p> Again, you can generalise using FsCheck: </p> <p> <pre>[<span style="color:#2b91af;">Property</span>(QuietOnSuccess&nbsp;=&nbsp;<span style="color:blue;">true</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;AddHasIdentity(<span style="color:#2b91af;">Angle</span>&nbsp;x) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(x,&nbsp;<span style="color:#2b91af;">Angle</span>.Identity.Add(x)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(x,&nbsp;x.Add(<span style="color:#2b91af;">Angle</span>.Identity)); }</pre> </p> <p> Once more, a reservation identical to the one given above must be given when it comes to floating point arithmetic. </p> <h3 id="c1fd56a6390148b6a74ba539096f8524"> Conclusion <a href="#c1fd56a6390148b6a74ba539096f8524" title="permalink">#</a> </h3> <p> The <code>Add</code> method is an associative, binary operation with identity; it's a monoid. </p> <p> As far as I can tell, any modulo-based addition is a monoid, but while, say, modulo 37 addition probably doesn't have any practical application, modulo 360 addition does, because it's how you do angular addition. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2017/10/10/strings-lists-and-sequences-as-a-monoid">Strings, lists, and sequences as a monoid</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Typing and testing problem 23 http://blog.ploeh.dk/2018/07/09/typing-and-testing-problem-23 2018-07-09T07:03:00+00:00 Mark Seemann <div id="post"> <p> <em>Yet another reflection on the relationship between types and tests, this time with a simple example.</em> </p> <p> The debate about dynamic typing versus static typing still goes on. If it ever gets resolved, I suppose it'll be in the far future. Until then, one's position is bound to be determined mostly by experience and belief. I openly admit that I prefer statically typed languages like <a href="http://fsharp.org">F#</a> and <a href="https://www.haskell.org">Haskell</a>. </p> <p> As I've <a href="http://blog.ploeh.dk/2016/02/10/types-properties-software">previously touched on</a>, I can't help seeing types as a <a href="https://en.wikipedia.org/wiki/Slider_(computing)">slider</a>. The more to the right you pull it, the stronger the type system. The more to the left you pull it, the more you'll need automated tests to give you a sense of confidence in your code. </p> <p> In this article, I'll share an small revelation recently given to me. </p> <h3 id="16a20a29aa8842ce94d78fba54b0dad9"> Problem 23 <a href="#16a20a29aa8842ce94d78fba54b0dad9" title="permalink">#</a> </h3> <p> Somewhere, a <a href="https://stackoverflow.com">Stack Overflow</a> user was going through <a href="https://wiki.haskell.org/H-99:_Ninety-Nine_Haskell_Problems">Ninety-Nine Haskell Problems</a>, and <a href="https://stackoverflow.com/q/46791466/126014">asked how to unit test problem 23</a>. </p> <p> The problem is elementary: <blockquote> <a href="https://wiki.haskell.org/99_questions/21_to_28">"Extract a given number of randomly selected elements from a list."</a> </blockquote> Here's an example of the intended use: </p> <p> <pre>λ&gt; rndSelect "abcdefgh" 3 "fag"</pre> </p> <p> The first argument to <code>rndSelect</code> is the candidates from which to pick elements; in this case the letters <em>a</em> to <em>h</em>. The second argument is the number of values to select; in this case the number <em>3</em>. </p> <h3 id="4d98d4998ffd4721b942a03649007f09"> Test plan <a href="#4d98d4998ffd4721b942a03649007f09" title="permalink">#</a> </h3> <p> How does one test a function like that? Clearly, when randomness is involved, you'll need some way to regulate the randomness in order to <a href="https://martinfowler.com/articles/nonDeterminism.html">make tests deterministic</a>. With my blinders on, I assumed that this was the main problem, so I answered with the following plan for a few properties: <ul> <li>The length of the returned list should be equal to the input length.</li> <li>All elements in the returned list should be elements of the list of candidates.</li> </ul> In addition, I also suggested a way to make tests deterministic, but I'll get back to that later. </p> <p> In response to this plan, the user <a href="https://stackoverflow.com/users/3234959">chi</a> commented on my second suggestion: <blockquote> "I think this it is a consequence of the free theorem. If so, no need to test for that!" </blockquote> Sometimes, I find it difficult to shake my object-oriented TDD-influenced way of thinking, but <em>chi</em> is right. Here's why: </p> <h3 id="1b301d9910e3472c9039094e6e737d91"> Parametric polymorphism <a href="#1b301d9910e3472c9039094e6e737d91" title="permalink">#</a> </h3> <p> .NET, including C# and F#, has a platform feature called <em>generics</em>. Haskell has generics as well, although normally, that language feature is called <em>parametric polymorphism</em>. What I had in mind was a set of parametrically polymorphic functions with these types: </p> <p> <pre><span style="color:#2b91af;">rndGenSelect</span>&nbsp;::&nbsp;(<span style="color:blue;">RandomGen</span>&nbsp;g,&nbsp;<span style="color:blue;">Integral</span>&nbsp;i)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;g&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[a]&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;i&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[a] <span style="color:#2b91af;">rndSelect</span>&nbsp;::&nbsp;<span style="color:blue;">Integral</span>&nbsp;i&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;[a]&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;i&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">IO</span>&nbsp;[a]</pre> </p> <p> Notice that both functions return lists of <code>a</code> values, where <code>a</code> is a type variable (in C#, you'd call it a <em>generic type argument</em>). It could be <code>Integer</code>, <code>String</code>, <code>Day</code>, or a custom domain type you'd added to the code base two minutes earlier. </p> <p> Given a completely unrestricted type variable, Haskell has no way of creating values. How could it, logically? </p> <p> In C#, you can write <code>default(T)</code>, which tends to mostly produce null references. Haskell doesn't have null, so with that option cut off, how would it be able to produce values of arbitrary types? It can't. </p> <p> When returning a list of <code>a</code> values, the only option open to a parametric polymorphic function is to pick values from its input arguments. For both <code>rndGenSelect</code> and <code>rndSelect</code>, there's only a single source of <code>a</code> values, so there's no reason to test that the functions return values from those lists of candidates. It's the only thing it can do. That's the <em>free theorem</em> for that function. </p> <p> It'd been an entirely different story if the function had had concrete types. If, for example, the function had had the type <code>RandomGen g =&gt; g -&gt; String -&gt; Int -&gt; String</code>, I could have written a function like this one: </p> <p> <pre><span style="color:#2b91af;">rndGenSelect&#39;</span>&nbsp;::&nbsp;<span style="color:blue;">RandomGen</span>&nbsp;g&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;g&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">String</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">Int</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">String</span> rndGenSelect&#39;&nbsp;_&nbsp;_&nbsp;count&nbsp;=&nbsp;<span style="color:blue;">replicate</span>&nbsp;count&nbsp;<span style="color:#a31515;">&#39;s&#39;</span> </pre> </p> <p> Because the type of elements is known at compile-time, we can pick an arbitrary <code>Char</code> value (<code>'s'</code>). This is possible because we know the type, and therefore can come up with a strategy to hard-code known values of that type. When the type argument is unknown, this is no longer possible. To paraphrase <a href="http://thecleancoder.blogspot.dk/2010/11/craftsman-63-specifics-and-generics.html">Robert C. Martin</a>, <em>as the types get more generic, the tests become more redundant</em>. </p> <h3 id="f7624b9d821c40a5b8a26de9f6a74120"> Taming randomness <a href="#f7624b9d821c40a5b8a26de9f6a74120" title="permalink">#</a> </h3> <p> Before we look at automated testing, let's consider how to turn randomness into deterministic behaviour. This is (seemingly) always a problem with unit testing when the desired behaviour contains randomness, because tests should be deterministic. Once again, however, it turns out that <a href="http://blog.ploeh.dk/2015/05/07/functional-design-is-intrinsically-testable">functional design is intrinsically testable</a>. Since Haskell design favours <a href="https://en.wikipedia.org/wiki/Pure_function">pure functions</a>, the core of <code>System.Random</code> is deterministic. </p> <p> This is, in fact, not much different from C#, where <a href="https://msdn.microsoft.com/en-us/library/system.random">the Random class</a> encapsulates an algorithm that computes a series of random-looking values based on an initial seed value. If you give it the same seed, it'll produce the same sequence of random-looking numbers. Haskell works the same way. </p> <p> This led me to a design with a 'core' function that does all the work, and a 'wrapper' function that only adds one extra feature: randomness. </p> <p> Starting my design with types, I wanted a function with this type: </p> <p> <pre><span style="color:#2b91af;">rndGenSelect</span>&nbsp;::&nbsp;(<span style="color:blue;">RandomGen</span>&nbsp;g,&nbsp;<span style="color:blue;">Integral</span>&nbsp;i)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;g&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[a]&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;i&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[a] </pre> </p> <p> This is the type that I've already discussed above. Because of the free theorem, we already know that the returned list can only contain values selected from the input list. In other words, there's no need to test for that. </p> <p> This function takes a <code>RandomGen</code> argument, which is a type class of pure functions. <code>RandomGen</code> itself is pure; the source of randomness comes from how it's produced. More on that later. This, however, should enable me to write deterministic tests. </p> <h3 id="47f98962da4c42beb96e32d2e1ec92ad"> Properties <a href="#47f98962da4c42beb96e32d2e1ec92ad" title="permalink">#</a> </h3> <p> Before we start adding deterministic tests, let's see how far we can get with property-based testing. First, designing with types, I need to implement the function so that it compiles. This is the simplest implementation I could think of: </p> <p> <pre><span style="color:#2b91af;">rndGenSelect</span>&nbsp;::&nbsp;(<span style="color:blue;">RandomGen</span>&nbsp;g,&nbsp;<span style="color:blue;">Integral</span>&nbsp;i)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;g&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[a]&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;i&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[a] rndGenSelect&nbsp;_&nbsp;xs&nbsp;_&nbsp;=&nbsp;[<span style="color:blue;">head</span>&nbsp;xs] </pre> </p> <p> This implementation is both incorrect and unsafe, but it compiles. In TDD fashion, then, I found it appropriate to add a test - in this case a <a href="https://hackage.haskell.org/package/QuickCheck">QuickCheck</a> property: </p> <p> <pre><span style="color:#2b91af;">lenProp</span>&nbsp;::&nbsp;<span style="color:blue;">Integral</span>&nbsp;i&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;<span style="color:#2b91af;">Int</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[a]&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">NonNegative</span>&nbsp;i&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">Bool</span> lenProp&nbsp;seed&nbsp;xs&nbsp;(NonNegative&nbsp;i)&nbsp;= &nbsp;&nbsp;i&nbsp;==&nbsp;genericLength&nbsp;(rndGenSelect&nbsp;(mkStdGen&nbsp;seed)&nbsp;xs&nbsp;i) </pre> </p> <p> This little piece of test code is the only surviving property from my original test plan. It states that for any non-negative count, the list returned from <code>rndGenSelect</code> should have the requested length. </p> <p> Writing this property, however, quickly forced me to deal with the case where the count is negative. It's easy to forget about edge cases when your function is nothing but a pie in the sky, but QuickCheck (and property-based testing in general) is really effective at grounding you in reality. Even with a language like Haskell, I still find the fast feedback loop from tests helpful. </p> <p> The original exercise specification doesn't mention what should happen if the count is negative, so after short deliberation, I decide to write another property: </p> <p> <pre><span style="color:#2b91af;">negLenProp</span>&nbsp;::&nbsp;<span style="color:blue;">Integral</span>&nbsp;i&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;<span style="color:#2b91af;">Int</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[a]&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Positive</span>&nbsp;i&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">Bool</span> negLenProp&nbsp;seed&nbsp;xs&nbsp;(Positive&nbsp;i)&nbsp;= &nbsp;&nbsp;0&nbsp;==&nbsp;genericLength&nbsp;(rndGenSelect&nbsp;(mkStdGen&nbsp;seed)&nbsp;xs&nbsp;(-i)) </pre> </p> <p> This property simply states that for all negative counts, the returned list should be empty. </p> <p> Both of these properties obviously fail, because of the incorrect implementation. </p> <p> The simplest implementation I could think of that passes both properties is this: </p> <p> <pre><span style="color:#2b91af;">rndGenSelect</span>&nbsp;::&nbsp;(<span style="color:blue;">RandomGen</span>&nbsp;g,&nbsp;<span style="color:blue;">Integral</span>&nbsp;i)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;g&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[a]&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;i&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[a] rndGenSelect&nbsp;_&nbsp;xs&nbsp;count&nbsp;=&nbsp;genericReplicate&nbsp;count&nbsp;(<span style="color:blue;">head</span>&nbsp;xs) </pre> </p> <p> At this point, I don't see how TDD or property-based testing can help me move forward. The remaining work required is to add randomness to the mix. In this case, I'll need to use the <code>RandomGen</code> argument to produce random values, but since I don't know how its algorithm works, then even if I had a seed value known at compile-time, I wouldn't be able to predict which values it'd produce. </p> <h3 id="9e2a643290b14a53bf8fc82d8773bb08"> Selecting random indices <a href="#9e2a643290b14a53bf8fc82d8773bb08" title="permalink">#</a> </h3> <p> I admit that I don't know how to write the next test a priori. I do know, however, that if I implement what's missing, I have a deterministic function, and I can use it to write regression test. In other words, I'll reverse direction and write the code first, and then the test. What a novel idea. </p> <p> <pre><span style="color:#2b91af;">rndGenSelect</span>&nbsp;::&nbsp;(<span style="color:blue;">RandomGen</span>&nbsp;g,&nbsp;<span style="color:blue;">Integral</span>&nbsp;i)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;g&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[a]&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;i&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[a] rndGenSelect&nbsp;rnd&nbsp;xs&nbsp;count&nbsp;= &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;indices&nbsp;=&nbsp;genericTake&nbsp;count&nbsp;$&nbsp;randomRs&nbsp;(0,&nbsp;<span style="color:blue;">length</span>&nbsp;xs&nbsp;-&nbsp;1)&nbsp;rnd &nbsp;&nbsp;<span style="color:blue;">in</span>&nbsp;<span style="color:blue;">fmap</span>&nbsp;(xs&nbsp;!!)&nbsp;indices </pre> </p> <p> This function first uses <code>randomRs</code> to produce an infinite list of values. These values are indices because they all fall between <code>0</code> and <code>length xs - 1</code>. In other words, they are indices into <code>xs</code>. </p> <p> While the list is infinite, it's lazily evaluated, so infinity itself isn't a problem. We only need <code>count</code> elements, though, so we can simply take the first <code>count</code> elements. </p> <p> Finally, the function maps over the list of indices, and for each index value, selects the element at that position. </p> <p> I could inline <code>indices</code> in the return expression, like this: </p> <p> <pre><span style="color:#2b91af;">rndGenSelect</span>&nbsp;::&nbsp;(<span style="color:blue;">RandomGen</span>&nbsp;g,&nbsp;<span style="color:blue;">Integral</span>&nbsp;i)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;g&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[a]&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;i&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[a] rndGenSelect&nbsp;rnd&nbsp;xs&nbsp;count&nbsp;= &nbsp;&nbsp;<span style="color:blue;">fmap</span>&nbsp;(xs&nbsp;!!)&nbsp;$&nbsp;genericTake&nbsp;count&nbsp;$&nbsp;randomRs&nbsp;(0,&nbsp;<span style="color:blue;">length</span>&nbsp;xs&nbsp;-&nbsp;1)&nbsp;rnd </pre> </p> <p> I find that more obscure than the first alternative, though, but both versions pass the properties and do what they're supposed to do. </p> <h3 id="c2e15aa34c4e4cb5bc0f7ad11580b711"> Regression testing <a href="#c2e15aa34c4e4cb5bc0f7ad11580b711" title="permalink">#</a> </h3> <p> How do I know that my code works? Well, that's always difficult with code that contains randomness, but you can load the function into GHCi and perform some <a href="https://en.wikipedia.org/wiki/Sanity_check">sanity testing</a>: </p> <p> <pre>λ&gt; rndGenSelect (mkStdGen 42) "foo" 3 "ofo" λ&gt; rndGenSelect (mkStdGen 1337) "bar" 10 "rabbaarrra" λ&gt; rndGenSelect (mkStdGen (-197221)) ['a'..'z'] 5 "ntfnc"</pre> </p> <p> That looks, I suppose, random enough... What's more important is that this is completely repeatable. This means that I can write <a href="http://blog.ploeh.dk/2018/04/30/parametrised-unit-tests-in-haskell">parametrised tests</a> that protect against regressions: </p> <p> <pre><span style="color:#a31515;">&quot;rndGenSelect&nbsp;of&nbsp;chars&nbsp;returns&nbsp;correct&nbsp;result&quot;</span>&nbsp;~:&nbsp;<span style="color:blue;">do</span> &nbsp;&nbsp;(seed,&nbsp;xs,&nbsp;count,&nbsp;expected)&nbsp;&lt;- &nbsp;&nbsp;&nbsp;&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;42,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;&nbsp;3,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#a31515;">&quot;ofo&quot;</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(&nbsp;&nbsp;&nbsp;1337,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#a31515;">&quot;bar&quot;</span>,&nbsp;10,&nbsp;<span style="color:#a31515;">&quot;rabbaarrra&quot;</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(-197221,&nbsp;[<span style="color:#a31515;">&#39;a&#39;</span>..<span style="color:#a31515;">&#39;z&#39;</span>],&nbsp;&nbsp;5,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#a31515;">&quot;ntfnc&quot;</span>) &nbsp;&nbsp;&nbsp;&nbsp;] &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;rnd&nbsp;=&nbsp;mkStdGen&nbsp;seed &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;actual&nbsp;=&nbsp;rndGenSelect&nbsp;rnd&nbsp;xs&nbsp;count &nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;$&nbsp;expected&nbsp;~=?&nbsp;actual </pre> </p> <p> These tests don't drive the design, but they prevent regressions. If, at a later time, I, or someone else, inadvertently revert <code>rndGenSelect</code> to <code>genericReplicate count (head xs)</code>, these tests will fail. </p> <h3 id="2f404b7e4e9c4b22ace4b0e738c58233"> Humble function <a href="#2f404b7e4e9c4b22ace4b0e738c58233" title="permalink">#</a> </h3> <p> The original problem statement is to write a function without an explicit <code>RandomGen</code> argument. In the spirit of <a href="http://bit.ly/xunitpatterns">xUnit Test Patterns'</a> <em>Humble Object</em> pattern, we can now click all our pieces together to a function that does what is required: </p> <p> <pre><span style="color:#2b91af;">rndSelect</span>&nbsp;::&nbsp;<span style="color:blue;">Integral</span>&nbsp;i&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;[a]&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;i&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">IO</span>&nbsp;[a] rndSelect&nbsp;xs&nbsp;count&nbsp;=&nbsp;<span style="color:blue;">do</span> &nbsp;&nbsp;rnd&nbsp;&lt;-&nbsp;newStdGen &nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;$&nbsp;rndGenSelect&nbsp;rnd&nbsp;xs&nbsp;count </pre> </p> <p> The only thing of interest here is that the function is impure, because it uses <code>newStdGen</code> to produce a random <code>RandomGen</code> value. It then delegates all work to <code>rndGenSelect</code>, which is covered by tests. </p> <p> As you can see, this function does <em>not</em> exhibit repeatable behaviour: </p> <p> <pre>λ&gt; rndSelect "abcdefgh" 3 "add" λ&gt; rndSelect "abcdefgh" 3 "daf"</pre> </p> <p> This should, I think, address the original problem statement. </p> <p> All source code for this article is <a href="https://github.com/ploeh/HasProblem23">available on GitHub</a>. </p> <h3 id="db2d673115f24bd2b4f4cbedae738342"> Summary <a href="#db2d673115f24bd2b4f4cbedae738342" title="permalink">#</a> </h3> <p> The first time I encountered parametric polymorphism was when C# got generics in 2005. Back then it was mostly explained as a mechanism to avoid <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing">boxing</a>, although it also seriously reduced the amount of boilerplate code you'd have to write in order to have type-safe collections. In many years, I mostly understood C# generics as a language feature aimed at efficiency and programmer productivity. </p> <p> It wasn't until I started to program in F#, with its stronger type inference, that it began to dawn on me that parametric polymorphism could also be a design tool. Making a function more generic tightens its contract, so to speak. The more generic a function becomes, the less wriggle room does it have. This may sound like a disadvantage to a programmer, but it's a boon to a <em>code reader</em>. When you, as a reader, encounter a parametrically polymorphic function, you already know that there are things that function can't do. Such functions come with invariants, or 'theorems', for free. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Terse operators make business code more readable http://blog.ploeh.dk/2018/07/02/terse-operators-make-business-code-more-readable 2018-07-02T12:00:00+00:00 Mark Seemann <div id="post"> <p> <em>Sometimes, terse operators can make code more readable. An article for all, even people who don't read Haskell code.</em> </p> <p> The <a href="https://www.haskell.org">Haskell</a> programming language has a reputation for being terse to the point of being unreadable. That reputation isn't undeserved, but to counter, other languages exist that are verbose to the point of being unreadable. </p> <p> Particularly, <a href="http://blog.ploeh.dk/2015/08/03/idiomatic-or-idiosyncratic">idiomatic</a> Haskell code involves abstruse operators like <code>.</code>, <code>$</code>, <code>&lt;$&gt;</code>, <code>&gt;&gt;=</code>, <code>&lt;*&gt;</code>, <code>&lt;&gt;</code>, and so on. Not only do such operators look scary, but when I started writing Haskell code, it also bothered me that I didn't know how to pronounce these operators. I don't know how you read code, but my brain often tries to 'talk' about the code, silently, inside my head, and when it encounters something like <code>=&lt;&lt;</code>, it tends to stumble. </p> <p> At least, it used to. These days, my brain has accepted that in many cases, Haskell operators are a little like punctuation marks. When I read a piece of prose, my brain doesn't insist on 'saying' <em>comma</em>, <em>semicolon</em>, <em>question mark</em>, <em>period</em>, etcetera. Such symbols assist reading, and often adjust the meaning of a text, but aren't to be read explicitly as themselves. </p> <p> I'm beginning to realise that Haskell operators work like that; sometimes, they fade into the background and assist reading. </p> <p> As a word of caution, don't take this analogy literally. Each Haskell operator means something specific, and they aren't interchangeable. Additionally, Haskell enables you to add your own custom operators, and I'm not sure that e.g. <a href="https://hackage.haskell.org/package/lens/docs/Control-Lens.html">lens</a> operators like <code>.~</code> or <code>%~</code> make code more readable. </p> <h3 id="53a6bd351c814befaa7d32e57a563f5a"> A simple business code example <a href="#53a6bd351c814befaa7d32e57a563f5a" title="permalink">#</a> </h3> <p> Forgetting about the lens operators, though, consider a piece of business code like this: </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> Please read on, even if you don't read Haskell code. I'm not going to walk you through the details of how the operators work. That's not the point of this article. The point is how the operators enable you to focus on the overall picture of what's going on. The full source code is <a href="https://github.com/ploeh/dependency-injection-revisited">available on GitHub</a>. </p> <p> To establish a bit of context, this function determines whether or not to accept a restaurant reservation. Even if you've never read Haskell code before, see if you can get a <em>sense</em> of what's going on. </p> <p> First, there's a <code>guard</code> which seems to involve whether or not the reservation is in the future. Second, there seems to be some calculations involving reservations, reserved seats, culminating in another <code>guard</code>. Third, the function seems to <code>create</code> a reservation by setting <code>reservationIsAccepted</code> to <code>True</code>. </p> <p> Granted, it probably helps if you know that both <code>=</code> and <code>&lt;-</code> bind the left-hand symbol to the expression on the right side. Additionally, after all this talk about special Haskell operators, it may not be immediately apparent that <code>+</code> is the perfectly normal addition operator, and <code>&lt;=</code> is the well-known <em>less-than-or-equal</em> relational operator. What if we keep those operators, and mask the rest with a white rectangle symbol (▯)? </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;▯&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;▯&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> Finally, you also ought to know that while Haskell code is read from top to bottom, you tend to read each expression from right to left. Armed with this knowledge, and by masking the operators, the business logic begins to stand out. </p> <p> First, it examines whether the <code>reservation</code> is in the future, and it does a <code>guard</code> of that. Again, I don't wish to make any claims that the code is magically self-documenting, because if you don't know what <code>guard</code> does, you don't know if this expression guards <em>against</em> the reservation being in the future, or if, conversely, it ensures that the reservation is in the future. It does the latter. </p> <p> Second, it conjures up some <code>reservations</code> from somewhere, by first getting the <code>reservationDate</code> from <code>reservation</code>, and then passing that value to <code>readReservations</code> (expressions are read from right to left). </p> <p> Moving on, it then calculates <code>reservedSeats</code> by starting with <code>reservations</code>, somehow extracting the <code>reservationQuantity</code> from those, and taking the <code>sum</code>. Since we've masked the operators, you can't tell exactly what's going on, but the gist is, hopefully, clear. </p> <p> The middle block of code concludes with another <code>guard</code>, this time ensuring that the <code>reservedSeats</code> plus the <code>reservationQuantity</code> is less than or equal to the <code>capacity</code>. </p> <p> Finally, the function sets <code>reservationIsAccepted</code> to <code>True</code> and calls <code>create</code>. </p> <p> What I find compelling about this is that the terseness of the Haskell operators enables you, a code reader, to scan the code to first understand the big picture. </p> <h3 id="16ce35c687e04ad1be79942884c27ccd"> Guards <a href="#16ce35c687e04ad1be79942884c27ccd" title="permalink">#</a> </h3> <p> Additionally, some common motifs begin to stand out. For example, there are two <code>guard</code> expressions. Because the operators are terse, the similarities stand out better. Let's juxtapose them: </p> <p> <pre>&nbsp;&nbsp;guard&nbsp;▯&nbsp;isReservationInFuture&nbsp;reservation &nbsp;&nbsp;guard&nbsp;▯&nbsp;reservedSeats&nbsp;+&nbsp;reservationQuantity&nbsp;reservation&nbsp;&lt;=&nbsp;capacity</pre> </p> <p> It seems clear that the same sort of thing is going on in both cases. There's a guard ensuring that a Boolean condition is satisfied. If you, however, reconsider the actual code, you'll see that the white rectangle hides two different operators: </p> <p> <pre>&nbsp;&nbsp;guard&nbsp;=&lt;&lt;&nbsp;isReservationInFuture&nbsp;reservation &nbsp;&nbsp;guard&nbsp;$&nbsp;reservedSeats&nbsp;+&nbsp;reservationQuantity&nbsp;reservation&nbsp;&lt;=&nbsp;capacity</pre> </p> <p> The reason for this is that it has to, because otherwise it wouldn't compile. <code>isReservationInFuture reservation</code> has the type <code>MaybeT ReservationsProgram Bool</code>. There's a Boolean value hidden in there, but it's buried inside a container. Using <code>=&lt;&lt;</code> enables you to pull out the Boolean value and pass it to <code>guard</code>. </p> <p> In the second <code>guard</code> expression, <code>reservedSeats + reservationQuantity&nbsp;reservation &lt;= capacity</code> is a 'naked' Boolean expression, so in this case you can use the <code>$</code> operator to pass it to <code>guard</code>. </p> <p> Haskellers may wonder why I chose <code>=&lt;&lt;</code> instead of the more common <code>&gt;&gt;=</code> operator in the first of the two <code>guard</code> expressions. I could have, but then the expression would have been this: </p> <p> <pre>&nbsp;&nbsp;isReservationInFuture&nbsp;reservation&nbsp;&gt;&gt;=&nbsp;guard</pre> </p> <p> The resulting behaviour is the same, but I think this obscures how the two <code>guard</code> expressions are variations on the same motif. </p> <p> The use of operators enables you to express code in such a way that motifs stand out. In contrast, I tried writing the same business functionality in <a href="http://fsharp.org">F#</a>, but it didn't come out as readable (in my opinion): </p> <p> <pre><span style="color:green;">//&nbsp;int&nbsp;-&gt;&nbsp;Reservation&nbsp;-&gt;&nbsp;ReservationsProgram&lt;int&nbsp;option&gt;</span> <span style="color:blue;">let</span>&nbsp;tryAccept&nbsp;capacity&nbsp;reservation&nbsp;=&nbsp;reservationsOption&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">do!</span>&nbsp;ReservationsOption.bind&nbsp;guard&nbsp;&lt;|&nbsp;isReservationInFuture&nbsp;reservation &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;reservations&nbsp;=&nbsp;readReservations&nbsp;reservation.Date &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;reservedSeats&nbsp;=&nbsp;List.sumBy&nbsp;(<span style="color:blue;">fun</span>&nbsp;r&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;r.Quantity)&nbsp;reservations &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">do!</span>&nbsp;guard&nbsp;(reservedSeats&nbsp;+&nbsp;reservation.Quantity&nbsp;&lt;=&nbsp;capacity) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return!</span>&nbsp;create&nbsp;{&nbsp;reservation&nbsp;<span style="color:blue;">with</span>&nbsp;IsAccepted&nbsp;=&nbsp;<span style="color:blue;">true</span>&nbsp;}&nbsp;}</pre> </p> <p> While you can also define custom operators in F#, it's rarely a good idea, for various reasons that, at its core, are related to how F# isn't Haskell. The lack of 'glue' operators in F#, though, obliged me to instead use the more verbose <code>ReservationsOption.bind</code>. This adds noise to the degree that the <code>guard</code> function disappears in the middle of the expression. The motif is fainter. </p> <h3 id="e476da4f87144f1d8b3c4f0766aab85e"> Piping <a href="#e476da4f87144f1d8b3c4f0766aab85e" title="permalink">#</a> </h3> <p> Another motif in Haskell code is <em>piping</em>. This is known from F# as well, where piping is normally done from left to right using the <code>|&gt;</code> operator. You can, as the above example shows, also use the right-to-left pipe operator <code>&lt;|</code>. In Haskell, expressions are idiomatically composed from right to left, often with the <code>$</code> operator, or, when using <a href="https://en.wikipedia.org/wiki/Tacit_programming">point-free</a> style, with the <code>.</code> operator. </p> <p> Once you realise that expressions compose from right to left, a masked expression like <code>sum ▯ reservationQuantity ▯ reservations</code> begins to look like a pipeline: start with <code>reservations</code>, somehow pipe them to <code>reservationQuantity</code>, and finally pipe the result of doing that to <code>sum</code>. That's actually not quite what happens, but I think that this compellingly communicates the overall idea: start with some reservations, consider their quantities, and calculate the sum of those. </p> <p> Another way to write that expression would be: </p> <p> <pre>&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;reservedSeats&nbsp;=&nbsp;<span style="color:blue;">sum</span>&nbsp;(<span style="color:blue;">fmap</span>&nbsp;reservationQuantity&nbsp;reservations)</pre> </p> <p> This implements the same behaviour as <code>sum $ reservationQuantity &lt;$&gt; reservations</code>, but once you get used to it, I like the operator-based alternative better. The operators fade into the background, enabling the flow of data to stand out better. </p> <h3 id="c78436b5007d4f569b5d619feb090caf"> Conclusion <a href="#c78436b5007d4f569b5d619feb090caf" title="permalink">#</a> </h3> <p> Haskell operators constitute the glue that enables you to compose expressions together. Often, you need to vary how expressions are composed together, because the types are slightly different. Picking an appropriate operator that composes particular expressions enables you to perform the composition with a high signal-to-noise ratio. </p> <p> Once you get used to reading Haskell code, the operators can fade into the background in well-factored code, just like punctuation marks assist you when you read prose. As always, this is no silver bullet. I've seen plenty of examples of obscure Haskell code as well, and copious use of operators is a fast way to obfuscate code. </p> <p> Use; punctuation? marks with. taste! </p> </div> <hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Visitor as a sum type http://blog.ploeh.dk/2018/06/25/visitor-as-a-sum-type 2018-06-25T14:31:00+00:00 Mark Seemann <div id="post"> <p> <em>The Visitor design pattern is isomorphic to sum types.</em> </p> <p> This article is part of <a href="http://blog.ploeh.dk/2018/03/05/some-design-patterns-as-universal-abstractions">a series of articles about specific design patterns and their category theory counterparts</a>. In it, you'll see how the <a href="https://en.wikipedia.org/wiki/Visitor_pattern">Visitor design pattern</a> is equivalent to a <a href="https://en.wikipedia.org/wiki/Tagged_union">sum type</a>. </p> <h3 id="ddc4643ff60949c382a9b631fe427cdd"> Sum types <a href="#ddc4643ff60949c382a9b631fe427cdd" title="permalink">#</a> </h3> <p> I think that the most important advantage of a statically typed programming language is that it gives you <a href="http://blog.ploeh.dk/2011/04/29/Feedbackmechanismsandtradeoffs">immediate feedback</a> on your design and implementation work. Granted, that your code compiles may not be enough to instil confidence that you've done the right thing, but it's obvious that when your code doesn't compile, you still have work to do. </p> <p> A static type system enables you to catch some programming errors at compile time. It prevents you from making obvious mistakes like trying to divide a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">GUID</a> by a date. Some type systems don't offer much more help than that, while others are more articulate; I think that <a href="http://blog.ploeh.dk/2016/02/10/types-properties-software">type systems inhabit a continuous spectrum of capabilities</a>, although that, too, is a simplification. </p> <p> An often-touted advantage of programming languages like <a href="http://fsharp.org">F#</a>, <a href="https://ocaml.org">OCaml</a>, and <a href="https://www.haskell.org">Haskell</a> is that they, in the words of <a href="https://twitter.com/yminsky">Yaron Minsky</a>, enable you to <em>make illegal states unrepresentable</em>. The way these languages differ from languages like C# and Java is that they have <a href="https://en.wikipedia.org/wiki/Algebraic_data_type">algebraic data types</a>. </p> <p> In short, algebraic data types distinguishes between <a href="https://en.wikipedia.org/wiki/Product_type">product types</a> and sum types. All statically typed language I've seen have product types, which you can think of as combinations of data. Objects with more than a single class fields would be product types. </p> <p> Sum types (also known as <em>discriminated unions</em>), on the other hand, are types that express mutually exclusive alternatives. Object-oriented programmers might mistake such a statement for sub-classing, but the difference is that object-oriented sub-classing creates a potentially infinite hierarchy of subtypes, while a sum type is statically constrained to a finite number of mutually exclusive cases. This is often useful. </p> <p> In this article, you'll see that a sum type is isomorphic to a corresponding Visitor. </p> <h3 id="dac9a78ee087418193fd776ceeade06b"> Church-encoded payment types <a href="#dac9a78ee087418193fd776ceeade06b" title="permalink">#</a> </h3> <p> In a previous article, you saw how to <a href="http://blog.ploeh.dk/2018/06/18/church-encoded-payment-types">Church-encode a domain-specific sum type</a>. That article, again, demonstrated how to rewrite <a href="http://blog.ploeh.dk/2016/11/28/easy-domain-modelling-with-types">a domain-specific F# discriminated union</a> as a C# API. The F# type was this <code>PaymentType</code> sum type: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;<span style="color:teal;">PaymentType</span>&nbsp;= |&nbsp;<span style="color:navy;">Individual</span>&nbsp;<span style="color:blue;">of</span>&nbsp;<span style="color:teal;">PaymentService</span> |&nbsp;<span style="color:navy;">Parent</span>&nbsp;<span style="color:blue;">of</span>&nbsp;<span style="color:teal;">PaymentService</span> |&nbsp;<span style="color:navy;">Child</span>&nbsp;<span style="color:blue;">of</span>&nbsp;originalTransactionKey&nbsp;:&nbsp;<span style="color:teal;">string</span>&nbsp;*&nbsp;paymentService&nbsp;:&nbsp;<span style="color:teal;">PaymentService</span></pre> </p> <p> Using Church-encoding in C#, you can arrive at this interface that models the same business problem: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IPaymentType</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;individual, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;parent, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">ChildPaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;child); }</pre> </p> <p> In order to use the API, the compiler obligates you to handle all three mutually exclusive cases defined by the three arguments to the <code>Match</code> method. Refer to the previous article for more details and code examples. All <a href="https://github.com/ploeh/ChurchEncoding">the C# code is also available on GitHub</a>. </p> <p> While the C# code works, I think it'd be a fair criticism to say that it doesn't feel object-oriented. Particularly the use of function delegates (<code>Func&lt;PaymentService, T&gt;</code>, etcetera) seems off. These days, C# is a multi-paradigmatic language, and function delegates have been around since 2007, so it's a perfectly fine C# design. Still, if we're trying to understand how object-oriented programming relates to fundamental programming abstractions, it behoves us to consider a more classic form of object-orientation. </p> <h3 id="19be9752ec8a44e18995db6c96c99bfe"> Introduce Parameter Object <a href="#19be9752ec8a44e18995db6c96c99bfe" title="permalink">#</a> </h3> <p> Through a series of refactorings you can transform the Church-encoded <code>IPaymentType</code> interface to a Visitor. The first step is to use <a href="http://amzn.to/YPdQDf">Refactoring</a>'s <em>Introduce Parameter Object</em> to turn the three method arguments of <code>Match</code> into a single object: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">PaymentTypeParameters</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;PaymentTypeParameters( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;individual, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;parent, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">ChildPaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;child) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Individual&nbsp;=&nbsp;individual; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Parent&nbsp;=&nbsp;parent; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Child&nbsp;=&nbsp;child; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;Individual&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;Parent&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">ChildPaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;Child&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} }</pre> </p> <p> The modified <code>IPaymentType</code> interface then looks like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IPaymentType</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">PaymentTypeParameters</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;parameters); }</pre> </p> <p> Clearly, this change means that you must also adjust each implementation of <code>IPaymentType</code> accordingly. Here's the <code>Match</code> method of <code>Individual</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">PaymentTypeParameters</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;parameters) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;parameters.Individual(paymentService); }</pre> </p> <p> The two other implementations (<code>Parent</code> and <code>Child</code>) change in the same way; the modifications are trivial, so I'm not going to show them here, but all the code is <a href="https://github.com/ploeh/ChurchEncoding/commit/64fa2638ffbdb81a077ac1dc3fbce697b3cba35b">available as a single commit</a>. </p> <p> Likewise, client code that uses the API needs adjustment, like the <code>ToJson</code> method: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span>&nbsp;ToJson(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IPaymentType</span>&nbsp;payment) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;payment.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">PaymentTypeParameters</span>&lt;<span style="color:#2b91af;">PaymentJsonModel</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;individual&nbsp;:&nbsp;ps&nbsp;=&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;">PaymentJsonModel</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;ps.Name, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Action&nbsp;=&nbsp;ps.Action, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;StartRecurrent&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TransactionKey&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Nothing</span>&lt;<span style="color:blue;">string</span>&gt;() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;parent&nbsp;:&nbsp;ps&nbsp;=&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;">PaymentJsonModel</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;ps.Name, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Action&nbsp;=&nbsp;ps.Action, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;StartRecurrent&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TransactionKey&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Nothing</span>&lt;<span style="color:blue;">string</span>&gt;() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;child&nbsp;:&nbsp;cps&nbsp;=&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;">PaymentJsonModel</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;cps.PaymentService.Name, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Action&nbsp;=&nbsp;cps.PaymentService.Action, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;StartRecurrent&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TransactionKey&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&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;">Just</span>&lt;<span style="color:blue;">string</span>&gt;(cps.OriginalTransactionKey) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;})); }</pre> </p> <p> From <a href="http://blog.ploeh.dk/2018/01/29/argument-list-isomorphisms">argument list isomorphisms</a> we know that an argument list is isomorphic to a Parameter Object, so this step should come as no surprise. We also know that the reverse translation (from Parameter Object to argument list) is possible. </p> <h3 id="496f81b27ad64feaaf0705eab578d9e8"> Add Run prefix <a href="#496f81b27ad64feaaf0705eab578d9e8" title="permalink">#</a> </h3> <p> I think it looks a little strange that the functions comprising <code>PaymentTypeParameters&lt;T&gt;</code> are named <code>Individual</code>, <code>Parent</code>, and <code>Child</code>. Functions <em>do</em> something, so they ought to be named with verbs. This turns out only to be an intermediary step, but I'll add the prefix <code>Run</code> to all three: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">PaymentTypeParameters</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;PaymentTypeParameters( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;individual, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;parent, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">ChildPaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;child) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;RunIndividual&nbsp;=&nbsp;individual; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;RunParent&nbsp;=&nbsp;parent; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;RunChild&nbsp;=&nbsp;child; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;RunIndividual&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;RunParent&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">ChildPaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;RunChild&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} }</pre> </p> <p> This doesn't change the structure of the code in any way, but sets it up for the next step. </p> <h3 id="690e226135a8414fbb122ffe834a5e87"> Refactor to interface <a href="#690e226135a8414fbb122ffe834a5e87" title="permalink">#</a> </h3> <p> The definition of <code>PaymentTypeParameters&lt;T&gt;</code> still doesn't look object-oriented. While it's formally an object, it's an object that composes three function delegates. We've managed to move the function delegates around, but we haven't managed to get rid of them. From <a href="http://blog.ploeh.dk/2018/02/12/object-isomorphisms">object isomorphisms</a>, however, we know that tuples of functions are isomorphic to objects, and that's essentially what we have here. In this particular case, there's no implementation code in <code>PaymentTypeParameters&lt;T&gt;</code> itself - it's nothing but a group of three functions. You can refactor that class to an interface: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IPaymentTypeParameters</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">T</span>&nbsp;RunIndividual(<span style="color:#2b91af;">PaymentService</span>&nbsp;individual); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">T</span>&nbsp;RunParent(<span style="color:#2b91af;">PaymentService</span>&nbsp;parent); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">T</span>&nbsp;RunChild(<span style="color:#2b91af;">ChildPaymentService</span>&nbsp;child); }</pre> </p> <p> The implementations of <code>Individual</code>, <code>Parent</code>, and <code>Child</code> don't change; only the signature of <code>Match</code> changes slightly: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IPaymentType</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">IPaymentTypeParameters</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;parameters); }</pre> </p> <p> Since this change removes the function delegates, it requires client code to change: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span>&nbsp;ToJson(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IPaymentType</span>&nbsp;payment) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;payment.Match(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">PaymentTypeToJsonParameters</span>()); } <span style="color:blue;">private</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">PaymentTypeToJsonParameters</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IPaymentTypeParameters</span>&lt;<span style="color:#2b91af;">PaymentJsonModel</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span>&nbsp;RunIndividual(<span style="color:#2b91af;">PaymentService</span>&nbsp;individual) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;individual.Name, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Action&nbsp;=&nbsp;individual.Action, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;StartRecurrent&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TransactionKey&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Nothing</span>&lt;<span style="color:blue;">string</span>&gt;() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span>&nbsp;RunParent(<span style="color:#2b91af;">PaymentService</span>&nbsp;parent) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;parent.Name, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Action&nbsp;=&nbsp;parent.Action, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;StartRecurrent&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TransactionKey&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Nothing</span>&lt;<span style="color:blue;">string</span>&gt;() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span>&nbsp;RunChild(<span style="color:#2b91af;">ChildPaymentService</span>&nbsp;child) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;child.PaymentService.Name, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Action&nbsp;=&nbsp;child.PaymentService.Action, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;StartRecurrent&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TransactionKey&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Just</span>&lt;<span style="color:blue;">string</span>&gt;(child.OriginalTransactionKey) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> The <code>ToJson</code> method now has to delegate to a <code>private</code> class that implements <code>IPaymentTypeParameters&lt;PaymentJsonModel&gt;</code>. In Java and F# you'd be able to pass an object expression, but in C# you have to create an explicit class for the purpose. The implementations of the three methods of the interface still correspond to the three functions the previous incarnations of the code used. </p> <h3 id="ca0c6f3576c74786b738f04904d79fb8"> Rename to Visitor <a href="#ca0c6f3576c74786b738f04904d79fb8" title="permalink">#</a> </h3> <p> At this point, the Visitor pattern's structure is already in place. The only remaining step is to rename the various parts of the API so that this becomes clear. You can start by renaming the <code>IPaymentTypeParameters&lt;T&gt;</code> interface to <code>IPaymentTypeVisitor&lt;T&gt;</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IPaymentTypeVisitor</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">T</span>&nbsp;VisitIndividual(<span style="color:#2b91af;">PaymentService</span>&nbsp;individual); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">T</span>&nbsp;VisitParent(<span style="color:#2b91af;">PaymentService</span>&nbsp;parent); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">T</span>&nbsp;VisitChild(<span style="color:#2b91af;">ChildPaymentService</span>&nbsp;child); }</pre> </p> <p> Notice that I've also renamed the methods from <code>RunIndividual</code>, <code>RunParent</code>, and <code>RunChild</code> to <code>VisitIndividual</code>, <code>VisitParent</code>, and <code>VisitChild</code>. </p> <p> Likewise, you can rename the <code>Match</code> method to <code>Accept</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IPaymentType</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Accept&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">IPaymentTypeVisitor</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;visitor); }</pre> </p> <p> In <a href="http://amzn.to/XBYukB">Design Patterns</a>, the Visitor design pattern is only described in such a way that both <code>Accept</code> and <code>Visit</code> methods have <code>void</code> return types, but from <a href="http://blog.ploeh.dk/2018/01/15/unit-isomorphisms">unit isomorphisms</a> we know that this is equivalent to returning <em>unit</em>. Thus, setting <code>T</code> in the above API to a suitable <em>unit</em> type (like the one defined in F#), you arrive at the canonical Visitor pattern. The generic version here is simply a generalisation. </p> <p> For the sake of completeness, client code now looks like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span>&nbsp;ToJson(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IPaymentType</span>&nbsp;payment) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;payment.Accept(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">PaymentTypeToJsonVisitor</span>()); } <span style="color:blue;">private</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">PaymentTypeToJsonVisitor</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IPaymentTypeVisitor</span>&lt;<span style="color:#2b91af;">PaymentJsonModel</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span>&nbsp;VisitIndividual(<span style="color:#2b91af;">PaymentService</span>&nbsp;individual) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;individual.Name, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Action&nbsp;=&nbsp;individual.Action, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;StartRecurrent&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TransactionKey&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Nothing</span>&lt;<span style="color:blue;">string</span>&gt;() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span>&nbsp;VisitParent(<span style="color:#2b91af;">PaymentService</span>&nbsp;parent) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;parent.Name, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Action&nbsp;=&nbsp;parent.Action, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;StartRecurrent&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TransactionKey&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Nothing</span>&lt;<span style="color:blue;">string</span>&gt;() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span>&nbsp;VisitChild(<span style="color:#2b91af;">ChildPaymentService</span>&nbsp;child) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;child.PaymentService.Name, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Action&nbsp;=&nbsp;child.PaymentService.Action, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;StartRecurrent&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TransactionKey&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Just</span>&lt;<span style="color:blue;">string</span>&gt;(child.OriginalTransactionKey) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> You can refactor all the <a href="http://blog.ploeh.dk/2018/05/22/church-encoding">other Church encoding examples I've shown you</a> to Visitor implementations. It doesn't always make the code more readable, but it's possible. </p> <h3 id="38f9e2c752e64c748d1799c2e32f37c1"> From Visitor to sum types <a href="#38f9e2c752e64c748d1799c2e32f37c1" title="permalink">#</a> </h3> <p> In this article, I've shown how to refactor from a Church-encoded sum type to a Visitor, using the following refactoring steps: <ol> <li>Introduce Parameter Object</li> <li>(Rename Method (by adding a <code>Run</code> prefix))</li> <li>Refactor to interface</li> <li>Rename to Visitor terminology</li> </ol> All those steps are, I believe, isomorphic, in that they have reverse translations. Thus, since (according to <a href="http://amzn.to/13tGJ0f">Conceptual Mathematics</a>) isomorphisms are transitive, the translation from sum type to Visitor must have a reverse translation as well. This also seems to me to be intuitively correct, as it's clear to me how to go the other way. Starting with a Visitor: <ol> <li>Refactor the Visitor interface to a Parameter Object that composes functions</li> <li>Refactor the Parameter Object to an argument list</li> <li>Rename types and members as desired</li> </ol> You can, I think, read this article from the bottom towards the top to get an impression of what such a series of refactorings would look like, so I'm not going to explicitly provide an example. </p> <h3 id="b5ac92e65f5d498289a2f99e2754ec00"> Summary <a href="#b5ac92e65f5d498289a2f99e2754ec00" title="permalink">#</a> </h3> <p> Algebraic data types enable you to <em>make illegal states unrepresentable</em>. Most programming languages have product types, so it's the lack of sum types that seems to make the difference between languages like C# and Java on the one side, and languages like F#, OCaml, or Haskell on the other side. </p> <p> You can, however, achieve the same objective with object-oriented design. The Visitor design pattern is equivalent to sum types, so everything you can express with a sum type in, say, F#, you can express with a Visitor in C#. </p> <p> That's not to say that these two representations are equal in readability or maintainability. F# and Haskell sum types are declarative types that usually only take up a few lines of code. Visitor, on the other hand, is a small object hierarchy; it's a more verbose way to express the idea that a type is defined by mutually exclusive and heterogeneous cases. I know which of these alternatives I prefer, but if I were caught in an object-oriented code base, it's nice to know that it's still possible to model a domain with algebraic data types. </p> </div> <hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Church-encoded payment types http://blog.ploeh.dk/2018/06/18/church-encoded-payment-types 2018-06-18T12:04:00+00:00 Mark Seemann <div id="post"> <p> <em>How to translate a domain-specific sum type into a Church-encoded C# API. An article for object-oriented developers.</em> </p> <p> This article is part of <a href="http://blog.ploeh.dk/2018/05/22/church-encoding">a series of articles about Church encoding</a>. In the previous articles, you've seen <a href="http://blog.ploeh.dk/2018/05/24/church-encoded-boolean-values">how to implement Boolean logic without Boolean primitives</a>, as well as <a href="http://blog.ploeh.dk/2018/05/28/church-encoded-natural-numbers">how to model natural numbers</a>, <a href="http://blog.ploeh.dk/2018/06/04/church-encoded-maybe">how to implement a Maybe container</a>, and <a href="http://blog.ploeh.dk/2018/06/11/church-encoded-either">how to implement an Either container</a>. Common to all four examples is that they're based on <a href="https://en.wikipedia.org/wiki/Tagged_union">sum types</a> with exactly two mutually exclusive cases. </p> <p> <img src="/content/binary/binary-sum-types-and-matching-methods.png" alt="Three binary sum types, and their corresponding match methods."> </p> <p> You may already have noticed that all three translate to <code>Match</code> methods that take two arguments. The translation is so mechanical that you could automate it. Each case in a sum type becomes an argument in a <code>Match</code> method. In this article, you'll see an example of a domain-specific sum type with three cases, translated to Church-encoding. </p> <h3 id="62f77838e7724b8e8b7b3e5361ae13a7"> A payment type model in F# <a href="#62f77838e7724b8e8b7b3e5361ae13a7" title="permalink">#</a> </h3> <p> In <a href="http://blog.ploeh.dk/2016/11/28/easy-domain-modelling-with-types">a previous article</a> I described a particular business problem that was elegantly addressed with a discriminated union (sum type) in F#: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;<span style="color:teal;">PaymentService</span>&nbsp;=&nbsp;{&nbsp;Name&nbsp;:&nbsp;<span style="color:teal;">string</span>;&nbsp;Action&nbsp;:&nbsp;<span style="color:teal;">string</span>&nbsp;} <span style="color:blue;">type</span>&nbsp;<span style="color:teal;">PaymentType</span>&nbsp;= |&nbsp;<span style="color:navy;">Individual</span>&nbsp;<span style="color:blue;">of</span>&nbsp;<span style="color:teal;">PaymentService</span> |&nbsp;<span style="color:navy;">Parent</span>&nbsp;<span style="color:blue;">of</span>&nbsp;<span style="color:teal;">PaymentService</span> |&nbsp;<span style="color:navy;">Child</span>&nbsp;<span style="color:blue;">of</span>&nbsp;originalTransactionKey&nbsp;:&nbsp;<span style="color:teal;">string</span>&nbsp;*&nbsp;paymentService&nbsp;:&nbsp;<span style="color:teal;">PaymentService</span></pre> </p> <p> In short, this model enables you to model various payments against a third-party payment service. An <em>individual</em> payment is, as the name implies, a single payment. A <em>parent</em> payment can be used to authorise a series of recurring, automated payments, for example to pay for a subscription. A <em>child</em> payment is one of those recurring payments; it must have a parent payment to authorise it, as automation means that no user interaction takes place. </p> <p> One task that is easily addressed with the above <code>PaymentType</code> discriminated union is that you can translate the data to JSON in a type-safe manner. The compiler will tell you whether or not you've handled all three cases. </p> <h3 id="bd590f5f56f7442ca2eddc89ffe07fea"> Auxiliary C# classes <a href="#bd590f5f56f7442ca2eddc89ffe07fea" title="permalink">#</a> </h3> <p> You can Church-encode <code>PaymentType</code> just like Boolean values, natural numbers, Maybe, and Either. Before you do that, however, you need to define the input types involved in each case. These are normal classes, although I prefer to make them immutable: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">PaymentService</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;PaymentService(<span style="color:blue;">string</span>&nbsp;name,&nbsp;<span style="color:blue;">string</span>&nbsp;action) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.Name&nbsp;=&nbsp;name; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.Action&nbsp;=&nbsp;action; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">string</span>&nbsp;Name&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">string</span>&nbsp;Action&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} } <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">ChildPaymentService</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;ChildPaymentService( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;originalTransactionKey, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">PaymentService</span>&nbsp;paymentService) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.OriginalTransactionKey&nbsp;=&nbsp;originalTransactionKey; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.PaymentService&nbsp;=&nbsp;paymentService; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">string</span>&nbsp;OriginalTransactionKey&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">PaymentService</span>&nbsp;PaymentService&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} }</pre> </p> <p> These are straightforward translations of the F# <code>PaymentService</code> record type, and the tuple associated with the <code>Child</code> case. In a real code base, I'd override <code>Equals</code> for both classes in order to turn them into proper <a href="https://en.wikipedia.org/wiki/Value_object">Value Objects</a>, but in order to keep the size of the code down, I omitted doing that here. </p> <h3 id="447c7cd04d0447ad99a034972134722b"> Church-encoded payment type <a href="#447c7cd04d0447ad99a034972134722b" title="permalink">#</a> </h3> <p> You can now translate the <code>PaymentType</code> F# discriminated union to a Church-encoded API in C#, starting with the interface: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IPaymentType</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;individual, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;parent, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">ChildPaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;child); }</pre> </p> <p> Since there's three cases in the sum type, that turns into a <code>Match</code> method with three arguments, each corresponding to one of the cases. As was also the case for the previous articles' <code>INaturalNumber</code>, <code>IMaybe&lt;T&gt;</code>, and <code>IEither&lt;L, R&gt;</code> interfaces, the data associated with each case is modelled as a function from the data to the generic return type <code>T</code>. </p> <p> Again, following the recipe implied by the previous examples, you should now add a concrete implementation of the <code>IPaymentType</code> interface for each case. It's natural to start with the first argument to the <code>Match</code> method, <em>individual:</em> </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Individual</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IPaymentType</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">PaymentService</span>&nbsp;paymentService; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Individual(<span style="color:#2b91af;">PaymentService</span>&nbsp;paymentService) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.paymentService&nbsp;=&nbsp;paymentService; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;individual, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;parent, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">ChildPaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;child) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;individual(paymentService); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> The <code>Individual</code> class <a href="https://en.wikipedia.org/wiki/Adapter_pattern">adapts</a> a <code>PaymentService</code> value, which it passes as the argument to the <code>individual</code> function argument when <code>Match</code> is called. As you've seen in the previous articles, a particular implementation uses only one of the method arguments, so the two other arguments, <code>parent</code> and <code>child</code>, are simply ignored. </p> <p> The <em>parent</em> implementation is almost identical: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Parent</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IPaymentType</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">PaymentService</span>&nbsp;paymentService; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Parent(<span style="color:#2b91af;">PaymentService</span>&nbsp;paymentService) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.paymentService&nbsp;=&nbsp;paymentService; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;individual, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;parent, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">ChildPaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;child) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;parent(paymentService); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> The <code>Parent</code> class also adapts a <code>PaymentService</code> value that it passes to a function when <code>Match</code> is called. The only difference is that it calls the <code>parent</code> function instead of the <code>individual</code> function argument. </p> <p> The third case is handled by the following <code>Child</code> class: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Child</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IPaymentType</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">ChildPaymentService</span>&nbsp;childPaymentService; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Child(<span style="color:#2b91af;">ChildPaymentService</span>&nbsp;childPaymentService) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.childPaymentService&nbsp;=&nbsp;childPaymentService; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;individual, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;parent, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">ChildPaymentService</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;child) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;child(childPaymentService); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> While the two other classes both adapt a <code>PaymentService</code> value, a <code>Child</code> object instead composes a <code>ChildPaymentService</code> value. When <code>Match</code> is called, it calls the <code>child</code> function argument with the composed value. </p> <h3 id="fbacd6c79ee04992a16bf6d81ecb2e3e"> Using the IPaymentType API <a href="#fbacd6c79ee04992a16bf6d81ecb2e3e" title="permalink">#</a> </h3> <p> One important feature that I originally had to implement was to translate a <em>payment type</em> value into a JSON document. For the purposes of this example, imagine that you can model the desired JSON document using this <a href="https://en.wikipedia.org/wiki/Data_transfer_object">Data Transfer Object</a>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">string</span>&nbsp;Name&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;">string</span>&nbsp;Action&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:#2b91af;">IChurchBoolean</span>&nbsp;StartRecurrent&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:#2b91af;">IMaybe</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;TransactionKey&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">set</span>;&nbsp;} }</pre> </p> <p> This is a mutable object because most .NET serialisation APIs require that the class in question has a parameterless constructor and writeable properties. Notice, however, that in order to demonstrate that all this code still doesn't rely on any primitive Boolean operators and such, the class' properties are defined as <code>IChurchBoolean</code> and <code>IMaybe&lt;string&gt;</code> values, as well as regular <code>string</code> values. </p> <p> Writing a method that translates any <code>IPaymentType</code> object into a <code>PaymentJsonModel</code> object is now straightforward: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">PaymentJsonModel</span>&nbsp;ToJson(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IPaymentType</span>&nbsp;payment) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;payment.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;individual&nbsp;:&nbsp;ps&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;">PaymentJsonModel</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;ps.Name, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Action&nbsp;=&nbsp;ps.Action, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;StartRecurrent&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TransactionKey&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Nothing</span>&lt;<span style="color:blue;">string</span>&gt;() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;parent&nbsp;:&nbsp;ps&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;">PaymentJsonModel</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;ps.Name, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Action&nbsp;=&nbsp;ps.Action, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;StartRecurrent&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TransactionKey&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Nothing</span>&lt;<span style="color:blue;">string</span>&gt;() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;child&nbsp;:&nbsp;cps&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;">PaymentJsonModel</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;cps.PaymentService.Name, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Action&nbsp;=&nbsp;cps.PaymentService.Action, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;StartRecurrent&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TransactionKey&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Just</span>&lt;<span style="color:blue;">string</span>&gt;(cps.OriginalTransactionKey) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); }</pre> </p> <p> Because the <code>Match</code> method takes three arguments, you have to supply a 'handler' function for each of them, and they all have to have the same return type. In this case they all return a new <code>PaymentJsonModel</code> object, so that requirement is fulfilled. All three lambda expressions simply copy over <code>Name</code> and <code>Action</code>, but they differ in the values they assign to <code>StartRecurrent</code> and <code>TransactionKey</code>. </p> <h3 id="465851b6143f4e75b1732bcfccdfcb28"> Tests <a href="#465851b6143f4e75b1732bcfccdfcb28" title="permalink">#</a> </h3> <p> In order to show you that it all works, here's a few examples I wrote as <a href="https://xunit.github.io">xUnit.net</a> tests: </p> <p> <pre>[<span style="color:#2b91af;">Fact</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;IndividualToJsonReturnsCorrectResult() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;sut&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Individual</span>(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">PaymentService</span>(<span style="color:#a31515;">&quot;MasterCard&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;Pay&quot;</span>)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;sut.ToJson(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#a31515;">&quot;MasterCard&quot;</span>,&nbsp;actual.Name); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#a31515;">&quot;Pay&quot;</span>,&nbsp;actual.Action); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.False(actual.StartRecurrent.ToBool()); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.True(actual.TransactionKey.IsNothing().ToBool()); } [<span style="color:#2b91af;">Fact</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;ParentToJsonReturnsCorrectResult() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;sut&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Parent</span>(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">PaymentService</span>(<span style="color:#a31515;">&quot;MasterCard&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;Pay&quot;</span>)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;sut.ToJson(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#a31515;">&quot;MasterCard&quot;</span>,&nbsp;actual.Name); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#a31515;">&quot;Pay&quot;</span>,&nbsp;actual.Action); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.True(actual.StartRecurrent.ToBool()); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.True(actual.TransactionKey.IsNothing().ToBool()); } [<span style="color:#2b91af;">Fact</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;ChildToJsonReturnsCorrectResult() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;sut&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Child</span>( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChildPaymentService</span>( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#a31515;">&quot;12345&quot;</span>, &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;">PaymentService</span>(<span style="color:#a31515;">&quot;MasterCard&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;Pay&quot;</span>))); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;sut.ToJson(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#a31515;">&quot;MasterCard&quot;</span>,&nbsp;actual.Name); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#a31515;">&quot;Pay&quot;</span>,&nbsp;actual.Action); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.False(actual.StartRecurrent.ToBool()); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#a31515;">&quot;12345&quot;</span>,&nbsp;actual.TransactionKey.Match(<span style="color:#a31515;">&quot;&quot;</span>,&nbsp;x&nbsp;=&gt;&nbsp;x)); }</pre> </p> <p> All three tests pass. </p> <h3 id="eceac90915cb40aab728fae7a36599d4"> Summary <a href="#eceac90915cb40aab728fae7a36599d4" title="permalink">#</a> </h3> <p> The major advantage of sum types in statically typed languages is that you can <em>make illegal states unrepresentable</em> (a maxim attributed to <a href="https://twitter.com/yminsky">Yaron Minsky</a>). Specifically, in the business example of payment types shown here, I need to be able to express that only three out of four combinations of <em>start recurrent</em> and <em>original transaction key</em> is legal. Specifically, I needed to express that the combination of <em>start recurrent = true</em> and the presence of a <em>transaction key</em> is illegal. Making such an illegal state unrepresentable is easy with a sum type, but as this article has shown, you can achieve the same goal in C#. </p> <p> With the API shown here, there's only three possible states (<code>Individual</code>, <code>Child</code>, and <code>Parent</code>). Notice that all three classes hide their data as <code>private</code> class fields, so the only way to extract that data is to call <code>Match</code>. The compiler will make sure that you handle all three cases, because you must supply a function for all three method arguments. </p> <p> The code shown in this article is <a href="https://github.com/ploeh/ChurchEncoding/tree/a015b6f2ce77ca4fbc2fa50c73e03c2bf9686b0c">available on GitHub</a>. </p> <p> This article concludes the little series on how to use Church-encoding in C# to create sum types. You may, however, think that it doesn't really feel object-oriented, with its heavy reliance on function arguments (e.g. <code>Func&lt;PaymentService, T&gt;</code>). It turns out, though, that with only a few refactorings, you'll come to the realisation that what you've seen here is <a href="http://blog.ploeh.dk/2018/01/08/software-design-isomorphisms">isomorphic</a> to a classic design pattern. <a href="http://blog.ploeh.dk/2018/06/25/visitor-as-a-sum-type">Read on!</a> </p> <p> <strong>Next: </strong> <a href="http://blog.ploeh.dk/2018/03/05/some-design-patterns-as-universal-abstractions">Some design patterns as universal abstractions</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Church-encoded Either http://blog.ploeh.dk/2018/06/11/church-encoded-either 2018-06-11T15:43:00+00:00 Mark Seemann <div id="post"> <p> <em>Programming languages don't have to have a built-in notion of error handling. You can implement sane error handling from first principles. An introduction for object-oriented programmers.</em> </p> <p> This article is part of <a href="http://blog.ploeh.dk/2018/05/22/church-encoding">a series of articles about Church encoding</a>. In this series, you'll learn how to re-create various programming language features from first principles. In previous articles, you learned <a href="http://blog.ploeh.dk/2018/05/24/church-encoded-boolean-values">how to implement Boolean logic without Boolean primitives</a>, <a href="http://blog.ploeh.dk/2018/05/28/church-encoded-natural-numbers">how to model natural numbers</a>, as well as <a href="http://blog.ploeh.dk/2018/06/04/church-encoded-maybe">how to implement Maybe</a> (a <a href="http://blog.ploeh.dk/2015/11/13/null-has-no-type-but-maybe-has">type-safe alternative to null</a>). Through these examples, you'll learn how to model <a href="https://en.wikipedia.org/wiki/Tagged_union">sum types</a> without explicit language support. </p> <p> <h3 id="6fd3652e6b9d462781a7d5191e32f6f0"> Error handling without exceptions <a href="#6fd3652e6b9d462781a7d5191e32f6f0" title="permalink">#</a> </h3> </p> <p> In a previous article, I've discussed how <a href="http://blog.ploeh.dk/2015/04/13/less-is-more-language-features">a language doesn't need to have built-in exceptions</a> in order to support composable and type-safe error handling. In fact, exceptions are noting but <a href="http://wiki.c2.com/?DontUseExceptionsForFlowControl">glorified GOTO statements</a>. A better approach is to use the <em>Either</em> abstraction, which enables you to model values that are either one or another thing. </p> <p> In <a href="https://fsharp.org">F#</a>, this type is known as <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/results">Result&lt;'T, 'TError&gt;</a>, while in <a href="https://www.haskell.org">Haskell</a> it's called <a href="https://hackage.haskell.org/package/base/docs/Data-Either.html">Either</a>. It enables you to model an outcome that is either something (like a success) or something else (such as an error). </p> <p> <a href="https://fsharpforfunandprofit.com">Scott Wlaschin</a> has already brilliantly described <a href="https://fsharpforfunandprofit.com/posts/recipe-part2">how this works in F#</a>, but the <code>Either</code> type can be used for error handling in Haskell in exactly the same way. When we use the terminology related to <em>either</em>, we distinguish between <em>left</em> and <em>right</em>. Typically, <em>right</em> is used to indicate success, via the pun that 'right' is 'correct'. </p> <p> <h3 id="72621c98299f4840b2ec880d254112a2"> Lambda calculus Either <a href="#72621c98299f4840b2ec880d254112a2" title="permalink">#</a> </h3> </p> <p> Church encoding is based on the <a href="https://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a>, which defines a universal model of computation based entirely on functions (lambda expressions) and recursion. As far as I can tell, you can define <em>Either</em> in lambda calculus as an expression that takes two arguments, and where there's two fundamental 'implementations' of the contract: </p> <p> <pre> left = λa.λl.λr.l a right = λb.λl.λr.r b</pre> </p> <p> (I admit that I'm going out on a limb here, since I haven't found any source that puts either in the above form, so I'd appreciate feedback if I did it incorrectly.) </p> <p> The contract is that, similar to <em>Maybe</em>, the <code>l</code> function argument represents the <em>left</em> case, whereas the <code>r</code> argument represents the <em>right</em> case. Contrary to <em>Maybe</em>, both <em>l</em> and <em>r</em> are used as functions. (Everything in lambda calculus is a function, but we don't always use the arguments as the function that they are.) </p> <p> The <code>left</code> function is a function that takes three arguments (<code>a</code>, <code>l</code>, and <code>r</code>) and always returns <code>l a</code>. Recall that in lambda calculus, everything is a function, which includes <code>l</code> (and <code>r</code>). In other words, <code>left</code> unconditionally calls <code>l</code> with <code>a</code>, and that's the return value. </p> <p> The <code>right</code> function works like the <code>left</code> function, with the only difference that it always returns <code>r b</code>. </p> <p> The idea, as usual, is that you can partially apply <code>left</code> and <code>right</code>, by, for instance calling <code>left three</code> (where <code>three</code> is the lambda calculus representation of the number 3, as described in <a href="http://blog.ploeh.dk/2018/05/28/church-encoded-natural-numbers">the article on Church-encoded natural numbers</a>). Such a partially applied function is a function that still takes the two arguments <code>l</code> and <code>r</code>. </p> <p> The same is true if you partially apply <code>right</code> with a value, like <code>right one</code>. </p> <p> In both cases, you have a function of the form <code>λl.λr.[...]</code>. If you've been given such a function by an external source, you may not know if it's a <code>left</code> or a <code>right</code> expression, and that's the point. You must supply handlers (<code>l</code> and <code>r</code>) that cover all possible cases. </p> <p> In the lambda calculus, expressions are always curried, so instead of viewing <code>left</code> and <code>right</code> as functions with three arguments, you can view them as functions that take a single element (<code>a</code> or <code>b</code>) and return functions that takes two arguments. This agrees with Haskell's <code>Left</code> and <code>Right</code> data constructors: </p> <p> <pre>Prelude&gt; :t Left Left :: a -&gt; Either a b Prelude&gt; :t Right Right :: b -&gt; Either a b</pre> </p> <p> Haskell tells us that <code>Left</code> is a function that takes an <code>a</code> value and returns an <code>Either a b</code> value. Similarly, <code>Right</code> is a function that takes a <code>b</code> value as input, and returns an <code>Either a b</code> </p> <p> <h3 id="a680dfb8fbb1483391de0ac3fedcdcd6"> Church-encoded Either in C# <a href="#a680dfb8fbb1483391de0ac3fedcdcd6" title="permalink">#</a> </h3> </p> <p> Both lambda calculus and Haskell relies on currying and partial application to make the contract fit. In C#, as you've <a href="http://blog.ploeh.dk/2018/01/08/software-design-isomorphisms">previously</a> seen, you can instead define an interface and rely on class fields for the 'extra' function arguments. Since Church-encoded Either is represented by a function that takes two arguments, we'll once again define an interface with a single method that takes two arguments: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IEither</span>&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">R</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;onLeft,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">R</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;onRight); }</pre> </p> <p> The <code>Match</code> method takes two functions as arguments, one that handles the <em>left</em> case, and one that handles the <em>right</em> case. They correspond to the <code>l</code> and <code>r</code> variables in the above lambda expressions. The intent, as with other Church-encoded discriminated unions, is that when client code is given an <code>IEither&lt;L, R&gt;</code> object, it can only interact with that object by telling the <code>Match</code> method how to deal with both cases. Only one of the functions will be called, but at compile-time, you don't know which one. Both functions, however, must return a value of the generic type <code>T</code>, and that's how you can translate an <code>IEither&lt;L, R&gt;</code> object to a <code>T</code> value. </p> <p> Following the normal procedure for Church encoding, you must also supply two implementations of the <code>IEither&lt;L, R&gt;</code> interface: one for each case. </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Left</span>&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">R</span>&gt;&nbsp;:&nbsp;<span style="color:#2b91af;">IEither</span>&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">R</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">L</span>&nbsp;left; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Left(<span style="color:#2b91af;">L</span>&nbsp;left) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.left&nbsp;=&nbsp;left; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;onLeft,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">R</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;onRight) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;onLeft(left); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> The <code>Left&lt;L, R&gt;</code> class is an <a href="https://en.wikipedia.org/wiki/Adapter_pattern">Adapter</a> of a value of the generic type <code>L</code> , making it appear as an <code>IEither&lt;L, R&gt;</code> object. </p> <p> It always calls the <code>onLeft</code> method argument with the adapted value <code>left</code>, while it ignores the <code>onRight</code> method argument. Since <code>onLeft</code> returns a <code>T</code> value, you can return the value produced by the function call. </p> <p> The <em>right</em> case is implemented in a similar fashion: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Right</span>&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">R</span>&gt;&nbsp;:&nbsp;<span style="color:#2b91af;">IEither</span>&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">R</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">R</span>&nbsp;right; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Right(<span style="color:#2b91af;">R</span>&nbsp;right) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.right&nbsp;=&nbsp;right; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;onLeft,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">R</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;onRight) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;onRight(right); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> The <code>Right&lt;L, R&gt;</code> class is the mirror image of <code>Left&lt;L, R&gt;</code>. Instead of adapting an <code>L</code> value, it adapts an <code>R</code> value. It implements <code>Match</code> by always calling <code>onRight</code> with the <code>right</code> value, which, again, produces a <code>T</code> value that can be immediately returned. </p> <p> Notice that for both implementations, the adapted values <code>left</code> and <code>right</code> are <code>private</code> class fields not exposed as public members. The only way you, as a caller, can potentially extract these values is by calling <code>Match</code>, and that forces you to explicitly deal with both cases. </p> <p> Here's an example of using the API: </p> <p> <pre>&gt; <span style="color:#2b91af;">IEither</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;e&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Right</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;(42); &gt; e.Match(s =&gt; s.Length % 2 == 0, i =&gt; i % 2 == 0) true</pre> </p> <p> I've deliberately declared <code>e</code> as a an <code>IEither&lt;string, int&gt;</code> in order to highlight the scenario where, as a client developer, you're often given a value of such a type, and you don't know if it's a <em>left</em> or a <em>right</em> value. Had I, instead, used the <code>var</code> keyword, the compiler would have detected that <code>e</code> is, really, a <code>Right&lt;string, int&gt;</code> variable. You may consider this choice artificial, but the point I'm trying to get across is that, when writing client code, you're often given a polymorphic value, and you don't know the concrete type of the value. According to the <a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle">Liskov Substitution Principle</a>, your client code must be able to deal with any subtype without changing the correctness of the system. In the case of an Either value, the way you deal with all subtypes is by supplying handlers for both cases to the <code>Match</code> method. </p> <p> In the above example, the return value is <code>true</code> because <code>42</code> is an even number. If, instead, the <code>e</code> object is a <em>left</em> case containing the string <code>"foo"</code>, the return value is <code>false</code> because the length of <code>"foo"</code> is <em>3</em> - an odd number: </p> <p> <pre>&gt; <span style="color:#2b91af;">IEither</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;e&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Left</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;(<span style="color:#a31515;">&quot;foo&quot;</span>); &gt; e.Match(s =&gt; s.Length % 2 == 0, i =&gt; i % 2 == 0) false</pre> </p> <p> Notice that the <code>e.Match</code> method call is the same in both examples; the <code>onLeft</code> and <code>onRight</code> functions are the same in both cases. The results differ because the input values represent different cases. </p> <p> If you've been following the overall series on Church encoding, you may think that it's cheating to use C#'s built-in <code>string</code> and <code>int</code> data types, but nothing prevents us from sticking to the data types we've built from scratch: </p> <p> <pre>&gt; <span style="color:#2b91af;">IEither</span>&lt;<span style="color:#2b91af;">IChurchBoolean</span>,&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&gt;&nbsp;e; &gt; e&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Right</span>&lt;<span style="color:#2b91af;">IChurchBoolean</span>,&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&gt;(<span style="color:#2b91af;">NaturalNumber</span>.Seven); &gt; e.Match(b&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchNot</span>(b),&nbsp;n&nbsp;=&gt;&nbsp;n.IsEven()) ChurchFalse { } &gt; e&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Left</span>&lt;<span style="color:#2b91af;">IChurchBoolean</span>,&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&gt;(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>()); &gt; e.Match(b&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchNot</span>(b),&nbsp;n&nbsp;=&gt;&nbsp;n.IsEven()) ChurchNot(ChurchFalse)</pre> </p> <p> For both the <em>left</em> and the <em>right</em> case, the <code>Match</code> inverts the Boolean expression if it's a <em>left</em> case, and evaluates if the number is even if it's a <em>right</em> case. In the first example, the return value is a <code>ChurchFalse</code> object because <em>7</em> is odd. In the second example, the return value is a <code>ChurchNot</code> object containing a <code>ChurchFalse</code> object (in other words, <em>true</em>), because the negation of <em>false</em> is <em>true</em>. </p> <p> <h3 id="f09ad4ad69ba47b6b9f13b0fcd99d6fe"> Either instead of exceptions <a href="#f09ad4ad69ba47b6b9f13b0fcd99d6fe" title="permalink">#</a> </h3> </p> <p> You can use Either to signal the success or failure of an operation. By convention, the <em>right</em> case is used to signal success, so, by elimination, <em>left</em> means failure. You can signal errors in numerous ways, e.g. by using <code>enum</code> values, but another common strategy is to simply use string values. </p> <p> Consider the following example. You receive a collection of values, where each element represents a vote for that element. For example, the list <em>Sandra, Zoey, Sandra</em> indicates two votes for <em>Sandra</em>, and one for <em>Zoey</em>. You need to write a method that returns the winner of a vote, but at least two distinct errors are possible: the input collection is empty, or there's a tie. </p> <p> You can model the error cases with an <code>enum</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">enum</span>&nbsp;<span style="color:#2b91af;">VoteError</span> { &nbsp;&nbsp;&nbsp;&nbsp;Empty&nbsp;=&nbsp;0, &nbsp;&nbsp;&nbsp;&nbsp;Tie }</pre> </p> <p> This enables you to write a method to find the winners, with an explicit Either return type: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IEither</span>&lt;<span style="color:#2b91af;">VoteError</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;FindWinner&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;votes) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;countedVotes&nbsp;=&nbsp;<span style="color:blue;">from</span>&nbsp;v&nbsp;<span style="color:blue;">in</span>&nbsp;votes &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">group</span>&nbsp;v&nbsp;<span style="color:blue;">by</span>&nbsp;v&nbsp;<span style="color:blue;">into</span>&nbsp;g &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;count&nbsp;=&nbsp;g.Count() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">orderby</span>&nbsp;count&nbsp;<span style="color:blue;">descending</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;<span style="color:blue;">new</span>&nbsp;{&nbsp;Vote&nbsp;=&nbsp;g.Key,&nbsp;Count&nbsp;=&nbsp;count&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;c&nbsp;=&nbsp;countedVotes.Take(2).Count(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(c&nbsp;==&nbsp;0) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Left</span>&lt;<span style="color:#2b91af;">VoteError</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">VoteError</span>.Empty); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;x0&nbsp;=&nbsp;countedVotes.ElementAt(0); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(c&nbsp;==&nbsp;1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Right</span>&lt;<span style="color:#2b91af;">VoteError</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;(x0.Vote); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;x1&nbsp;=&nbsp;countedVotes.ElementAt(1); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(Equals(x0.Count,&nbsp;x1.Count)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Left</span>&lt;<span style="color:#2b91af;">VoteError</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">VoteError</span>.Tie); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Right</span>&lt;<span style="color:#2b91af;">VoteError</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;(x0.Vote); }</pre> </p> <p> Notice that the return type of the <code>FindWinner</code> method is <code>IEither&lt;VoteError, T&gt;</code>; either you get a <code>VoteError</code> value, or you get a <code>T</code> value, but any client code doesn't know which it'll be, so it must handle both cases. </p> <p> The method uses a C# query expression to group, count, and order the votes. If there's no elements, the return value is a <em>left</em> value containing <code>VoteError.Empty</code>. If there's only a single vote group (e.g. if the votes where all for <em>Sandra</em>), that value is returned in a <em>right</em> case. Otherwise, if the two highest ranked votes have the same count, a <em>left</em> value is returned containing <code>VoteError.Tie</code>. Finally, in all other cases, the highest voted element is returned in a <em>right</em> case. </p> <p> Here's some examples in <em>C# Interactive:</em> </p> <p> <pre>&gt; FindWinner&lt;<span style="color:blue;">int</span>&gt;() Left&lt;VoteError, int&gt;(Empty) &gt; FindWinner(1, 2, 3, 1, 4, 2) Left&lt;VoteError, int&gt;(Tie) &gt; FindWinner(<span style="color:#a31515;">&quot;Sandra&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;Zoey&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;Sandra&quot;</span>) Right&lt;VoteError, string&gt;("Sandra")</pre> </p> <p> Instead of throwing two different types of exceptions on invalid input, the <code>FindWinner</code> method handles invalid input as <em>left</em> cases, and valid input as the <em>right</em> case. You can do that consistently, and thereby eliminate the need for exceptions. Errors are, instead, reported as <em>left</em> values. </p> <p> <h3 id="fb2ac51484e14b738c2e4af5278912e3"> Summary <a href="#fb2ac51484e14b738c2e4af5278912e3" title="permalink">#</a> </h3> </p> <p> In this article, you saw how it's possible to define the <em>Either</em> container from first principles, using nothing but functions (and, for the C# examples, interfaces and classes in order to make the code easier to understand for object-oriented developers). </p> <p> The code shown in this article is <a href="https://github.com/ploeh/ChurchEncoding/tree/49b0646c38d15648e9145052d3a04954f54c29f8">available on GitHub</a>. </p> <p> <a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">Like Maybe</a>, you can also make Either a functor. This'll enable you to compose various error-producing functions in a sane manner. </p> <p> Church-encoding enables you to model sum types as functions. So far in this article series, you've seen how to model Boolean values, natural numbers, Maybe, and Either. Common to all four examples is that the data type in question consists of two mutually exclusive cases. This is the reason they're all modelled as methods that take two arguments. What happens if, instead of two, you have <em>three</em> mutually exclusive cases? Read on. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/06/18/church-encoded-payment-types">Church-encoded payment types</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Church-encoded Maybe http://blog.ploeh.dk/2018/06/04/church-encoded-maybe 2018-06-04T10:08:00+00:00 Mark Seemann <div id="post"> <p> <em>Programming languages don't have to have a built-in notion of null values. Missing or optional values can be created from first principles. An introduction for object-oriented programmers.</em> </p> <p> This article is part of <a href="http://blog.ploeh.dk/2018/05/22/church-encoding">a series of articles about Church encoding</a>. In this series, you'll learn how to re-create various programming language features from first principles. In previous articles, you learned <a href="http://blog.ploeh.dk/2018/05/24/church-encoded-boolean-values">how to implement Boolean logic without Boolean primitives</a>, as well as <a href="http://blog.ploeh.dk/2018/05/28/church-encoded-natural-numbers">how to model natural numbers</a>. Through these examples, you'll learn how to model <a href="https://en.wikipedia.org/wiki/Tagged_union">sum types</a> without explicit language support. </p> <h3 id="2e26f3d3d84a43b790f7ee5e89dedbff"> The billion-dollar mistake <a href="#2e26f3d3d84a43b790f7ee5e89dedbff" title="permalink">#</a> </h3> <p> All mainstream programming languages have a built-in notion of <em>null</em>: a value that isn't there. There's nothing wrong with the concept; you often run into situations where you need to return a value, but in certain cases, you'll have nothing to return. Division by zero would be one example. Attempting to retrieve the first element from an empty collection would be another. </p> <p> Unfortunately, for fifty years, we've been immersed in environments where null references have been the dominant way to model the absence of data. This, despite the fact that even <a href="https://en.wikipedia.org/wiki/Tony_Hoare">Sir Antony Hoare</a>, the inventor of null references, has publicly called it his <em>billion-dollar mistake</em>. </p> <p> You can, however, model the potential absence of data in saner ways. <a href="https://www.haskell.org">Haskell</a>, for example, has no built-in null support, but it does include a built-in <a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">Maybe</a> type. In Haskell (as well as in <a href="http://fsharp.org">F#</a>, where it's called <code>option</code>), <code>Maybe</code> is defined as a sum type: </p> <p> <pre><span style="color:blue;">data</span>&nbsp;Maybe&nbsp;a&nbsp;=&nbsp;Nothing&nbsp;|&nbsp;Just&nbsp;a&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#2b91af;">Eq</span>,&nbsp;<span style="color:#2b91af;">Ord</span>)</pre> </p> <p> If you're not familiar with Haskell syntax, this is a type declaration that states that the <a href="https://en.wikipedia.org/wiki/Parametric_polymorphism">parametrically polymorphic</a> (AKA <em>generic</em>) data type <code>Maybe</code> is inhabited by <code>Just</code> values that contain other values, plus the constant <code>Nothing</code>. </p> <p> This article series, however, examines how to implement sum types with Church encoding. </p> <h3 id="b2a73bd4fc25450a8ba2e5e90f3319dc"> Lambda calculus maybe <a href="#b2a73bd4fc25450a8ba2e5e90f3319dc" title="permalink">#</a> </h3> <p> Church encoding is based on the <a href="https://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a>, which defines a universal model of computation based entirely on functions (lambda expressions) and recursion. In lambda calculus, the contract of <em>Maybe</em> is defined as an expression that takes two arguments. <a href="http://programmable.computer/posts/church_encoding.html">There's two fundamental 'implementations' of the contract</a>: </p> <p> <pre>nothing = λn.λj.n just = λx.λn.λj.j x</pre> </p> <p> The contract is that the first function argument (<code>n</code>) represents the <em>nothing</em> case, whereas the second argument (<code>j</code>) represents the <code>just</code> case. </p> <p> The <code>nothing</code> function is a lambda expression that takes two arguments (<code>n</code> and <code>j</code>), and always returns the first, left-most argument (<code>n</code>). </p> <p> The <code>just</code> function is a lambda expression that takes three arguments (<code>x</code>, <code>n</code>, and <code>j</code>), and always returns <code>j x</code>. Recall that in the lambda calculus, everything is a function, including <code>j</code>, so <code>j x</code> means that the function <code>j</code> is called with the argument <code>x</code>. </p> <p> A few paragraphs above, I wrote that the contract of <em>maybe</em> is modelled as an expression that takes two arguments, yet <code>just</code> takes three arguments. How does that fit? </p> <p> In the lambda calculus, expressions are always curried, so instead of viewing <code>just</code> as a function with three arguments, you can view it as a function that takes a single element (<code>x</code>) and returns a function that takes two arguments. This agrees with Haskell's <code>Just</code> data constructor: </p> <p> <pre>Prelude&gt; :t Just Just :: a -&gt; Maybe a</pre> </p> <p> Haskell tells us that <code>Just</code> is a function that takes an <code>a</code> value (corresponding to <code>x</code> in the above <code>just</code> lambda expression) and returns a <code>Maybe a</code> value. </p> <h3 id="01738cd9f37e4067947379b2aaf1735c"> Church-encoded Maybe in C# <a href="#01738cd9f37e4067947379b2aaf1735c" title="permalink">#</a> </h3> <p> Both lambda calculus and Haskell rely on currying and partial application to make the contract fit. In C#, as you've <a href="http://blog.ploeh.dk/2018/01/08/software-design-isomorphisms">previously</a> seen, you can instead define an interface and rely on class fields for the 'extra' function arguments. Since Church-encoded Maybe is represented by a function that takes two arguments, we'll once again define an interface with a single method that takes two arguments: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<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> In the first article, about Church-encoded Boolean values, you saw how two mutually exclusive values could be modelled as a method that takes two arguments. Boolean values are simply constants (<em>true</em> and <em>false</em>), where the next example (natural numbers) included a case where one case (<em>successor</em>) contained data. In that example, however, the data was statically typed as another <code>INaturalNumber</code> value. In the current <code>IMaybe&lt;T&gt;</code> example, the data contained in the <em>just</em> case is generic (it's of the type <code>T</code>). </p> <p> Notice that there's two levels of generics in play. <code>IMaybe&lt;T&gt;</code> itself is a container of the generic type <code>T</code>, whereas <code>Match</code> enables you to convert the container into the rank-2 polymorphic type <code>TResult</code>. </p> <p> Once more, the contract of <code>IMaybe&lt;T&gt;</code> is that the first, left-hand argument represents the <em>nothing</em> case, whereas the second, right-hand argument represents the <em>just</em> case. The <em>nothing</em> implementation, then, is similar to the previous <code>ChurchTrue</code> and <code>Zero</code> classes: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Nothing</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;:&nbsp;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<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) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;nothing; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Again, the implementation unconditionally returns <code>nothing</code> while ignoring <code>just</code>. You may, though, have noticed that, as is appropriate for Maybe, <code>Nothing&lt;T&gt;</code> has a distinct type. In other words, <code>Nothing&lt;string&gt;</code> doesn't have the same type as <code>Nothing&lt;int&gt;</code>. This is not only 'by design', but is a fundamental result of how we define <em>Maybe</em>. The code simply wouldn't compile if you tried to remove the type argument from the class. This is in contrast to <a href="http://blog.ploeh.dk/2015/11/13/null-has-no-type-but-maybe-has">C# null, which has no type</a>. </p> <p> You implement the <em>just</em> case like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Just</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;:&nbsp;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;value; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Just(<span style="color:#2b91af;">T</span>&nbsp;value) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.value&nbsp;=&nbsp;value; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<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) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;just(value); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> According to the contract, <code>Just&lt;T&gt;</code> ignores <code>nothing</code> and works exclusively with the <code>just</code> function argument. Notice that the <code>value</code> class field is <code>private</code> and not exposed as a public member. The only way you, as a caller, can potentially extract the value is by calling <code>Match</code>. </p> <p> Here are some examples of using the API: </p> <p> <pre>&gt; <span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Nothing</span>&lt;<span style="color:#2b91af;">Guid</span>&gt;().Match(nothing:&nbsp;<span style="color:#a31515;">&quot;empty&quot;</span>,&nbsp;just:&nbsp;g&nbsp;=&gt;&nbsp;g.ToString()) "empty" &gt; <span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Just</span>&lt;<span style="color:blue;">int</span>&gt;(42).Match(nothing:&nbsp;<span style="color:#a31515;">&quot;empty&quot;</span>,&nbsp;just:&nbsp;i&nbsp;=&gt;&nbsp;i.ToString()) "42" &gt; <span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Just</span>&lt;<span style="color:blue;">int</span>&gt;(1337).Match(nothing:&nbsp;0,&nbsp;just:&nbsp;i&nbsp;=&gt;&nbsp;i) 1337</pre> </p> <p> Notice that the third example shows how to extract the value contained in a <code>Nothing&lt;int&gt;</code> object without changing the output type. All you have to do is to supply a 'fall-back' value that can be used in case the value is <em>nothing</em>. </p> <h3 id="8af13110cd88473c97cc1cee28dd7ee9"> Maybe predicates <a href="#8af13110cd88473c97cc1cee28dd7ee9" title="permalink">#</a> </h3> <p> You can easily implement the standard Maybe predicates <code>IsNothing</code> and <code>IsJust</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;IsNothing&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;m) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;m.Match&lt;<span style="color:#2b91af;">IChurchBoolean</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nothing&nbsp;:&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>(),&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;just&nbsp;:&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;IsJust&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;m) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;m.Match&lt;<span style="color:#2b91af;">IChurchBoolean</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nothing&nbsp;:&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;just&nbsp;:&nbsp;_&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>()); }</pre> </p> <p> Here, I arbitrarily chose to implement <code>IsJust</code> 'from scratch', but I could also have implemented it by negating the result of calling <code>IsNothing</code>. Once again, notice that the predicates are expressed in terms of Church-encoded Boolean values, instead of the built-in <code>bool</code> primitives. </p> <h3 id="76561f015e4d4da0a590ba247eb4500d"> Functor <a href="#76561f015e4d4da0a590ba247eb4500d" title="permalink">#</a> </h3> <p> From Haskell (and F#) we know that Maybe is a <a href="http://blog.ploeh.dk/2018/03/22/functors">functor</a>. In C#, you turn a container into a functor by implementing an appropriate <code>Select</code> method. You can do this with <code>IMaybe&lt;T&gt;</code> as well: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IMaybe</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;">IMaybe</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;">IMaybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nothing:&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Nothing</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;just:&nbsp;x&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Just</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;(selector(x))); }</pre> </p> <p> Notice that this method turns an <code>IMaybe&lt;T&gt;</code> object into an <code>IMaybe&lt;TResult&gt;</code> object, using nothing but the <code>Match</code> method. This is possible because <code>Match</code> has a generic return type; thus, among other types of values, you can make it return <code>IMaybe&lt;TResult&gt;</code>. </p> <p> When <code>source</code> is a <code>Nothing&lt;T&gt;</code> object, <code>Match</code> returns the object in the <em>nothing</em> case, which here becomes a new <code>Nothing&lt;TResult&gt;</code> object. </p> <p> When <code>source</code> is a <code>Just&lt;T&gt;</code> object, <code>Match</code> invokes <code>selector</code> with the value contained in the <em>just</em> object, packages the result in a new <code>Just&lt;TResult&gt;</code> object, and returns it. </p> <p> Because the <code>Select</code> method has the correct signature, you can use it with query syntax, as well as with normal method call syntax: </p> <p> <pre><span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;m&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Just</span>&lt;<span style="color:blue;">int</span>&gt;(42); <span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;actual&nbsp;=&nbsp;<span style="color:blue;">from</span>&nbsp;i&nbsp;<span style="color:blue;">in</span>&nbsp;m &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;i.ToString();</pre> </p> <p> This example simply creates a <em>just</em> value containing the number <code>42</code>, and then maps it to a string. Another way to write the same expression would be with method call syntax: </p> <p> <pre><span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;m&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Just</span>&lt;<span style="color:blue;">int</span>&gt;(42); <span style="color:#2b91af;">IMaybe</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;actual&nbsp;=&nbsp;m.Select(i&nbsp;=&gt;&nbsp;i.ToString());</pre> </p> <p> In both cases, the result is a <em>just</em> case containing the string <code>"42"</code>. </p> <h3 id="4bdd2b27f1724e3198b95d86642c8a6c"> Summary <a href="#4bdd2b27f1724e3198b95d86642c8a6c" title="permalink">#</a> </h3> <p> In this article, you saw how it's possible to define the <em>Maybe</em> container from first principles, using nothing but functions (and, for the C# examples, interfaces and classes in order to make the code easier to understand for object-oriented developers). </p> <p> The code shown in this article is <a href="https://github.com/ploeh/ChurchEncoding/tree/8d1e7501f486351e748646c915f0bd334332e386">available on GitHub</a>. </p> <p> Church-encoding enables you to model sum types as functions. So far in this article series, you've seen how to model Boolean values, natural numbers, and Maybe. Common to all three examples is that the data type in question consists of two mutually exclusive cases. There's at least one more interesting variation on that pattern. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/06/11/church-encoded-either">Church-encoded Either</a>. </p> </div> <div id="comments"> <hr> <h2 id="comments-header">Comments</h2> <div class="comment" id="219468451d9a4af99be169a73af898bd"> <div class="comment-author"><a href="https://github.com/adleatherwood">Anthony Leatherwood</a></div> <div class="comment-content"> It's probably not your favorite thing to do anymore, but I thank you so much for continuing to provide C# examples for these concepts. It's invaluable for programmers wishing to adopt these concepts into the OOP languages they work with for a living. It's also a tremendous aid in briding the gap of understanding between OOP and FP. </div> <div class="comment-date">2018-06-04 17:57 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Church-encoded natural numbers http://blog.ploeh.dk/2018/05/28/church-encoded-natural-numbers 2018-05-28T08:24:00+00:00 Mark Seemann <div id="post"> <p> <em>Natural numbers don't have to be built into programming languages. An introduction for object-oriented programmers.</em> </p> <p> This article is part of <a href="http://blog.ploeh.dk/2018/05/22/church-encoding">a series of articles about Church encoding</a>. The previous article, about <a href="http://blog.ploeh.dk/2018/05/24/church-encoded-boolean-values">Church-encoding of Boolean values</a>, concluded with the question: <em>how do you determine whether an integer is even or odd?</em> </p> <p> That sounds easy, but turns out to be more complicated that you might think at first glance. </p> <h3 id="47669f1d5f3c48968e13474ec60a86a0"> Built-in options <a href="#47669f1d5f3c48968e13474ec60a86a0" title="permalink">#</a> </h3> <p> How would you normally check whether a number is even? In some languages, like <a href="https://www.haskell.org">Haskell</a>, it's built into the base library: </p> <p> <pre>Prelude&gt; even 1337 False Prelude&gt; even 42 True</pre> </p> <p> In C#, surprisingly, I don't think it's built-in, but it's easy to implement a method to answer the question: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;IsEven(<span style="color:blue;">this</span>&nbsp;<span style="color:blue;">int</span>&nbsp;i) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;i&nbsp;%&nbsp;2&nbsp;==&nbsp;0; }</pre> </p> <p> You could implement an <code>IsOdd</code> method either by using the <code>!=</code> operator instead of <code>==</code>, but otherwise copy the implementation of <code>IsEven</code>; or, alternatively, call <code>IsEven</code> and negate the result. </p> <p> This works fine in normal C# code, but in this article, the agenda is different. We're investigating how programming with the <a href="http://blog.ploeh.dk/2018/05/24/church-encoded-boolean-values">previous article's</a> <code>IChurchBoolean</code> API would look. The above built-in options use Boolean language primitives, so that's not really instructive. </p> <h3 id="313b328dd4f2495b852ef2a7aae6b130"> Boolean conversions <a href="#313b328dd4f2495b852ef2a7aae6b130" title="permalink">#</a> </h3> <p> It's easy to convert between Church-encoded Boolean values and built-in Boolean values. For reasons I'll explain shortly, I still don't think that's instructive in this particular context, but for good measure I'll cover how to do it. </p> <p> A method like the above <code>IsEven</code> returns <code>bool</code>. If you, instead, want an <code>IChurchBoolean</code>, you can use this simple conversion method: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;ToChurchBoolean(<span style="color:blue;">this</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;b) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(b) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">else</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>(); }</pre> </p> <p> Alternatively, you can also use the ternary operator, but an ugly cast is necessary to make the C# compiler happy: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;ToChurchBoolean(<span style="color:blue;">this</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;b) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;b&nbsp;?&nbsp;(<span style="color:#2b91af;">IChurchBoolean</span>)<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>()&nbsp;:&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>(); }</pre> </p> <p> Regardless of which implementation you choose, you'd be able to interact with the result as an <code>IChurchBoolean</code> values, as this small interactive session demonstrates: </p> <p> <pre>&gt; 42.IsEven().ToChurchBoolean().Match(<span style="color:#a31515;">&quot;Even&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;Odd&quot;</span>) "Even" &gt; 1337.IsEven().ToChurchBoolean().Match(<span style="color:#a31515;">&quot;Even&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;Odd&quot;</span>) "Odd"</pre> </p> <p> Still, converting from <code>bool</code> to <code>IChurchBoolean</code> doesn't address the underlying question: <em>is it possible to write programs without built-in Boolean primitives?</em> </p> <p> The conversion function <code>ToChurchBoolean</code> uses built-in Boolean values and functions, so it doesn't show whether or not it would be possible to make do without those. </p> <p> Before we abandon that line of inquiry, however, I think it's only fair to share a conversion method that goes the other way: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;ToBool(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;b) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;b.Match(<span style="color:blue;">true</span>,&nbsp;<span style="color:blue;">false</span>); }</pre> </p> <p> This function enables you to convert an <code>IChurchBoolean</code> value into a primitive C# <code>bool</code>, because when <code>b</code> represents <em>true</em>, the first argument (i.e. <code>true</code>) is returned, and when <code>b</code> represents <em>false</em>, the second argument (i.e. <code>false</code>) is returned. </p> <h3 id="5a59bcde604b4444b7dba56a6ed1989f"> Peano numbers <a href="#5a59bcde604b4444b7dba56a6ed1989f" title="permalink">#</a> </h3> <p> If we can't use built-in primitives or operators that return them (e.g. <code>==</code>), we may not be able to move forward with built-in numbers, either. What we <em>can</em> do, however, is to follow the <a href="https://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a> to implement <a href="https://en.wikipedia.org/wiki/Natural_number">natural numbers</a> using Church encoding. This will enable us to determine if a natural number is even or odd. </p> <p> Lambda calculus models natural numbers according to <a href="https://en.wikipedia.org/wiki/Peano_axioms">Peano's model</a>. In short, a natural number is either zero (or one, depending on the specific interpretation), or a successor to another natural number. As an example, using the <code>Successor</code> class that I'll develop later in this article, the number three can be represented as <code>new Successor(new Successor(new Successor(new Zero())))</code> - it's the number after the number after the number after zero. </p> <p> Like Church-encoded Boolean values, a Church-encoded natural number is a function that takes two arguments, corresponding to zero, and a successor function: </p> <p> <pre>zero = λf.λx.x one = λf.λx.f x two = λf.λx.f (f x) three = λf.λx.f (f (f x)) ...</pre> </p> <p> Each of these functions takes an initial value <code>x</code>, as well as a function <code>f</code>. In the lambda calculus, neither <code>x</code> nor <code>f</code> have any implied interpretation; it's the number of applications of <code>f</code> that defines the number. </p> <p> In most translations into programming languages that I've encountered, however, <code>x</code> is usually interpreted as zero, and <code>f</code> as the <a href="https://en.wikipedia.org/wiki/Successor_function">successor function</a>. In Haskell, for example, <a href="https://wiki.haskell.org/Peano_numbers">a common way to model Peano numbers</a> is to use a <a href="https://en.wikipedia.org/wiki/Tagged_union">sum type</a>: </p> <p> <pre><span style="color:blue;">data</span>&nbsp;Peano&nbsp;=&nbsp;Zero&nbsp;|&nbsp;Succ&nbsp;Peano&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#2b91af;">Eq</span>,&nbsp;<span style="color:#2b91af;">Show</span>) </pre> </p> <p> Basically, this means that a value of the <code>Peano</code> type can either be the atom <code>Zero</code>, or a <code>Succ</code> value. Notice that <code>Succ</code> contains another <code>Peano</code> value; the data type is recursive. </p> <p> You can write Haskell values like these: </p> <p> <pre>*Peano&gt; zero = Zero *Peano&gt; one = Succ Zero *Peano&gt; two = Succ (Succ Zero) *Peano&gt; three = Succ (Succ (Succ Zero))</pre> </p> <p> Alternatively, you can also define the numbers based on previous definitions: </p> <p> <pre>*Peano&gt; zero = Zero *Peano&gt; one = Succ zero *Peano&gt; two = Succ one *Peano&gt; three = Succ two</pre> </p> <p> This variation of Peano numbers uses an explicit sum type, but as the lambda calculus representation suggests, you can also use Church encoding to represent the two cases. </p> <h3 id="144967cc5ba04aac979242c5032b7a96"> Church-encoded natural numbers <a href="#144967cc5ba04aac979242c5032b7a96" title="permalink">#</a> </h3> <p> If you recall Church-encoded Boolean values, you may remember that they are functions that take two values: a value to be used in case of <em>true</em>, and a value to be used in the case of <em>false</em>. You can do something similar with natural numbers. <code>Zero</code> is like <em>true</em> and <em>false</em>, in the sense that it's nothing but a label without any associated data. <code>Succ</code>, on the other hand, contains another <code>Peano</code> value. The way to do that is to turn the <em>successor</em> case into a function. Doing that, you'll arrive at an interface like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">T</span>&nbsp;zero,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">INaturalNumber</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;succ); }</pre> </p> <p> The first argument, on the left-hand side, is the case to use when an object represents <em>zero</em>. The second argument, on the right-hand side, is a function that will ultimately produce the value associated with a <em>successor</em>. The implied contract here is that the <code>INaturalNumber</code> passed as input to <code>succ</code> is the <em>predecessor</em> to 'the current value'. This may seem counter-intuitive, but hopefully becomes clearer when you see the <code>Successor</code> class below. The crucial insight is that a successor value has no intrinsic value; it's entirely defined by how many predecessors it has. </p> <p> The <em>zero</em> implementation is similar to how Church-encoding implements <em>true</em>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Zero</span>&nbsp;:&nbsp;<span style="color:#2b91af;">INaturalNumber</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">T</span>&nbsp;zero,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">INaturalNumber</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;succ) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;zero; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Notice that the <code>Zero</code> class implements <code>INaturalNumber</code> by always returning <code>zero</code>, and consequently always ignoring <code>succ</code>. </p> <p> Another class, <code>Successor</code>, handles the right-hand side of the <code>Match</code> method: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Successor</span>&nbsp;:&nbsp;<span style="color:#2b91af;">INaturalNumber</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;predecessor; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Successor(<span style="color:#2b91af;">INaturalNumber</span>&nbsp;n) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.predecessor&nbsp;=&nbsp;n; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">T</span>&nbsp;zero,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">INaturalNumber</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;succ) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;succ(predecessor); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Notice that <code>Successor</code> composes its <code>predecessor</code> via Constructor Injection, and unconditionally calls <code>succ</code> with its <code>predecessor</code> when <code>Match</code> is invoked. </p> <h3 id="8ea8a3a6f4b245a3b7375da29ec4c93c"> Working with natural numbers <a href="#8ea8a3a6f4b245a3b7375da29ec4c93c" title="permalink">#</a> </h3> <p> What can you do with this <code>INaturalNumber</code> API, then? </p> <p> Initially, you can define some numbers, like the above Haskell examples: </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;">NaturalNumber</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;&nbsp;Zero&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Zero</span>(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;&nbsp;&nbsp;One&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Successor</span>(Zero); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;&nbsp;&nbsp;Two&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Successor</span>(One); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;Three&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Successor</span>(Two); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;&nbsp;Four&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Successor</span>(Three); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;&nbsp;Five&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Successor</span>(Four); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;&nbsp;&nbsp;Six&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Successor</span>(Five); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;Seven&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Successor</span>(Six); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;Eight&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Successor</span>(Seven); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">INaturalNumber</span>&nbsp;&nbsp;Nine&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Successor</span>(Eight); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;More&nbsp;memmbers&nbsp;go&nbsp;here...</span> }</pre> </p> <p> Here, I arbitrarily chose to define the numbers from zero to nine, but you could go on for as long as you care. </p> <p> You can also convert these Church-encoded numbers to primitive <code>int</code> values, like this: </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.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;p&nbsp;=&gt;&nbsp;1&nbsp;+&nbsp;p.Count()); }</pre> </p> <p> Here are some examples from a C# Interactive session: </p> <p> <pre>&gt; <span style="color:#2b91af;">NaturalNumber</span>.Zero.Count() 0 &gt; <span style="color:#2b91af;">NaturalNumber</span>.One.Count() 1 &gt; <span style="color:#2b91af;">NaturalNumber</span>.Seven.Count() 7</pre> </p> <p> The implementation of <code>Count</code> is recursive. When <code>n</code> is a <code>Zero</code> instance, it'll return the first argument (<code>0</code>), but when it's a <code>Successor</code>, it'll invoke the lambda expression <code>p =&gt; 1 + p.Count()</code>. Notice that this lambda expression recursively calls <code>Count</code> on <code>p</code>, which is the <code>Successor</code>'s <code>predecessor</code>. It'll keep doing that until it reaches a <code>Zero</code> instance. </p> <p> Recursion is a central part of the lambda calculus; you can't do anything useful without it. If you're a C# or Java programmer, you may be concerned, because recursion tends to be problematic in such languages. Deeply recursive functions will sooner or later crash because of a stack overflow. </p> <p> You shouldn't, however, be concerned. First, I'm not trying to convince you to write all your future C# or Java code using Church-encoded numbers and Boolean values. The point of this article series is to investigate the fundamentals of computations, and to gain a better understanding of sum types. As such, the code examples presented here are only demonstrations of the underlying principles. Lambda calculus itself serves the same purpose: it's a universal model of computation; it wasn't intended to be a practical programming language - in fact, there were no programmable computers in 1936. </p> <p> Furthermore, the problem with recursion causing stack overflow isn't universal. Languages like <a href="http://fsharp.org">F#</a> and Haskell support <a href="https://en.wikipedia.org/wiki/Tail_call">tail recursion</a>, thereby enabling recursive functions to run to arbitrary depths. </p> <h3 id="a13730f3e8c54cd98beb1801b07a4707"> Pattern matching <a href="#a13730f3e8c54cd98beb1801b07a4707" title="permalink">#</a> </h3> <p> In the previous article, I hinted that there's a reason I decided to name the interface method <code>Match</code>. This is because it looks a lot like <a href="https://en.wikipedia.org/wiki/Pattern_matching">pattern matching</a>. In F#, you could write <code>count</code> like this: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;Peano&nbsp;=&nbsp;Zero&nbsp;|&nbsp;Succ&nbsp;<span style="color:blue;">of</span>&nbsp;Peano <span style="color:green;">//&nbsp;Peano&nbsp;-&gt;&nbsp;int</span> <span style="color:blue;">let</span>&nbsp;<span style="color:blue;">rec</span>&nbsp;count&nbsp;n&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;n&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;Zero&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;0 &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;Succ&nbsp;p&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;1&nbsp;+&nbsp;count&nbsp;p</pre> </p> <p> This implementation, by the way, isn't tail-recursive, but you can <a href="http://blog.ploeh.dk/2015/12/22/tail-recurse">easily refactor to a tail-recursive implementation</a> like this: </p> <p> <pre><span style="color:green;">//&nbsp;Peano&nbsp;-&gt;&nbsp;int</span> <span style="color:blue;">let</span>&nbsp;count&nbsp;n&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;<span style="color:blue;">rec</span>&nbsp;countImp&nbsp;acc&nbsp;n&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;n&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;Zero&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;acc &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;Succ&nbsp;p&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;countImp&nbsp;(1&nbsp;+&nbsp;acc)&nbsp;p &nbsp;&nbsp;&nbsp;&nbsp;countImp&nbsp;0&nbsp;n</pre> </p> <p> Both variations use the <code>match</code> keyword to handle both the <code>Zero</code> and the <code>Succ</code> case for any <code>Peano</code> value <code>n</code>. That's already close to the above C# code, but using the optional C# language feature of <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments">named arguments</a>, you can rewrite the implementation of <code>Count</code> to this: </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.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;zero:&nbsp;0, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;succ:&nbsp;p&nbsp;=&gt;&nbsp;1&nbsp;+&nbsp;p.Count()); }</pre> </p> <p> This starts to look like pattern matching of sum types in F#. The argument names aren't required, but using them makes it clearer which cases the <code>Match</code> method handles. </p> <h3 id="f4beca2d1da24362b4c43cf1f6528616"> Addition <a href="#f4beca2d1da24362b4c43cf1f6528616" title="permalink">#</a> </h3> <p> You can now start to add features and capabilities to the natural numbers API. An obvious next step is to 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.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;zero:&nbsp;y, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;succ:&nbsp;p&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Successor</span>(p.Add(y))); }</pre> </p> <p> Again, the implementation is recursive. When <code>x</code> is <code>zero</code>, you simply return <code>y</code>, because <em>zero + y</em> is <em>y</em>. When <code>x</code> is a <code>Successor</code>, you recursively add <code>y</code> to its <code>predecessor</code>, and put the result in a new <code>Successor</code>. You can think of the predecessor <code>p</code> as one less than the successor. By recursively subtracting one from any <code>Successor</code> object, you'll eventually match the <code>zero</code> case, which will then return <code>y</code>. When the stack unrolls, each stack puts the previous result into a new <code>Successor</code>. This happens exactly the correct number of times corresponding to the value of <code>x</code>, because that's the size of the stack when <code>Add</code> hits <code>zero</code>. </p> <p> Here are some examples: </p> <p> <pre>&gt; <span style="color:#2b91af;">NaturalNumber</span>.One.Add(<span style="color:#2b91af;">NaturalNumber</span>.Two).Count() 3 &gt; <span style="color:#2b91af;">NaturalNumber</span>.Four.Add(<span style="color:#2b91af;">NaturalNumber</span>.Three).Count() 7 &gt; <span style="color:#2b91af;">NaturalNumber</span>.Seven.Add(<span style="color:#2b91af;">NaturalNumber</span>.Six).Count() 13</pre> </p> <p> You can also implement multiplication, but that's a bit more complicated, and not relevant to the topic of this article (which is how to determine if a number is even or odd). </p> <h3 id="ceb31f7122ea4b258b26d038f0d247bf"> Testing for zero <a href="#ceb31f7122ea4b258b26d038f0d247bf" title="permalink">#</a> </h3> <p> In addition to basic arithmetic, you can also define functions that tell you something about a natural number. We'll start gently with a function that tells us whether or not a number is zero: </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.Match&lt;<span style="color:#2b91af;">IChurchBoolean</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;zero:&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;succ:&nbsp;_&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>()); }</pre> </p> <p> The <code>IsZero</code> method simply returns a <code>ChurchTrue</code> object when <code>n</code> is a <code>Zero</code> instance, and a <code>ChurchFalse</code> object for all other numbers. </p> <p> You can see that this works in this C# Interactive session: </p> <p> <pre>&gt; <span style="color:#2b91af;">NaturalNumber</span>.Two.IsZero() ChurchFalse { } &gt; <span style="color:#2b91af;">NaturalNumber</span>.Zero.IsZero() ChurchTrue { } &gt; <span style="color:#2b91af;">NaturalNumber</span>.Three.IsZero() ChurchFalse { }</pre> </p> <p> You can also <code>Match</code> on the returned Boolean value to return e.g. a string: </p> <p> <pre>&gt; <span style="color:#2b91af;">NaturalNumber</span>.Nine.IsZero().Match(trueCase:&nbsp;<span style="color:#a31515;">&quot;Zero&quot;</span>,&nbsp;falseCase:&nbsp;<span style="color:#a31515;">&quot;Not&nbsp;zero&quot;</span>) "Not zero" &gt; <span style="color:#2b91af;">NaturalNumber</span>.Zero.IsZero().Match(trueCase:&nbsp;<span style="color:#a31515;">&quot;Zero&quot;</span>,&nbsp;falseCase:&nbsp;<span style="color:#a31515;">&quot;Not&nbsp;zero&quot;</span>) "Zero"</pre> </p> <p> This already demonstrates that you can implement predicates and branching logic from first principles, without resorting to built-in Boolean primitives or operators. </p> <h3 id="c131713ecba247f98cc1b93e0fb8451b"> Detecting even numbers <a href="#c131713ecba247f98cc1b93e0fb8451b" title="permalink">#</a> </h3> <p> Testing whether a natural number is even or uneven requires a bit more work. It's probably easiest to understand if we first consider an F# implementation: </p> <p> <pre><span style="color:green;">//&nbsp;Peano&nbsp;-&gt;&nbsp;ChurchBoolean</span> <span style="color:blue;">let</span>&nbsp;<span style="color:blue;">rec</span>&nbsp;isEven&nbsp;n&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;n&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;Zero&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;ChurchTrue &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;Succ&nbsp;Zero&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;ChurchFalse &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;Succ&nbsp;(Succ&nbsp;p)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;isEven&nbsp;p</pre> </p> <p> Zero is even, so when <code>n</code> matches <code>Zero</code>, <code>isEven</code> returns <code>ChurchTrue</code>. Conversely, when the input is <code>Succ Zero</code> (i.e. <em>one</em>), the return value is <code>ChurchFalse</code> because <em>one</em> is odd. </p> <p> The <em>zero</em> and <em>one</em> cases serve as exit cases for the recursive algorithm. Since we've handled <code>Zero</code> and <code>Succ Zero</code> (that is, <em>zero</em> and <em>one</em>), we know that any other case must be at least twice nested. This means that the <code>Succ (Succ p)</code> pattern matches all other cases. You can think of <code>p</code> as <em>n - 2</em>. </p> <p> The algorithm proceeds to recursively call <code>isEven</code> with <code>p</code> (i.e. <em>n - 2</em>). Sooner or later, these recursive function calls will match either the <code>Zero</code> or the <code>Succ Zero</code> case, and exit with the appropriate return value. </p> <p> C# doesn't have as sophisticated pattern matching features as F#, so we're going to have to figure out how implement this algorithm without relying on a nested pattern like <code>Succ (Succ p)</code>. As an initial step, we can rewrite the function in F#, using two matches instead of one: </p> <p> <pre><span style="color:green;">//&nbsp;Peano&nbsp;-&gt;&nbsp;ChurchBoolean</span> <span style="color:blue;">let</span>&nbsp;<span style="color:blue;">rec</span>&nbsp;isEven&nbsp;n&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;n&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;Zero&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;ChurchTrue &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;Succ&nbsp;p1&nbsp;<span style="color:blue;">-&gt;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;p1&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;Zero&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;ChurchFalse &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;Succ&nbsp;p2&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;isEven&nbsp;p2</pre> </p> <p> This isn't as elegant as the previous implementation, but on the other hand, it's straightforward to translate to C#: </p> <p> <pre><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.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;zero:&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>(),&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;0&nbsp;is&nbsp;even,&nbsp;so&nbsp;true</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;succ:&nbsp;p1&nbsp;=&gt;&nbsp;p1.Match(&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;Match&nbsp;previous</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;zero:&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>(),&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;If&nbsp;0&nbsp;then&nbsp;successor&nbsp;was&nbsp;1</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;succ:&nbsp;p2&nbsp;=&gt;&nbsp;p2.IsEven()));&nbsp;<span style="color:green;">//&nbsp;Eval&nbsp;previous&#39;&nbsp;previous</span> }</pre> </p> <p> Like in the F# example, when <code>n</code> is a <code>Zero</code> object, it'll return the value associated with the <code>zero</code> case. Since zero is even, it returns a <code>ChurchTrue</code> object. </p> <p> In all other cases, a <code>Match</code> on the predecessor <code>p1</code> is required. If that nested match is <code>zero</code>, then we know that <code>n</code> must have been <em>one</em>, since the the predecessor turned out to be <em>zero</em>. In that case, then, return a <code>ChurchFalse</code> object, because <em>one</em> isn't even. </p> <p> The nested <code>Match</code> considers the predecessor <code>p1</code>. In the <code>succ</code> case of the nested <code>Match</code>, then, we can consider <code>p2</code>; that is, the predecessor to the predecessor to <code>n</code> - in other words: <em>n - 2</em>. The function recursively calls itself with <em>n - 2</em>, and it'll keep doing so until it matches either the <em>zero</em> or the <em>one</em> case. </p> <p> The implementation works: </p> <p> <pre>&gt; <span style="color:#2b91af;">NaturalNumber</span>.Two.IsEven() ChurchTrue { } &gt; <span style="color:#2b91af;">NaturalNumber</span>.Three.IsEven() ChurchFalse { }</pre> </p> <p> <code>IsEven</code> is implemented from first principles. The only language features we need are lambda expressions and recursion, although in order to make these examples slightly more <a href="http://blog.ploeh.dk/2015/08/03/idiomatic-or-idiosyncratic">idiomatic</a>, I've also used interfaces and classes. </p> <h3 id="d4be671469fb4f529db9afd3e2626dd1"> Detecting odd numbers <a href="#d4be671469fb4f529db9afd3e2626dd1" title="permalink">#</a> </h3> <p> You could implement a corresponding <code>IsOdd</code> method similarly to <code>IsEven</code>, but it's easier to use the Boolean operators already in place from the previous article: </p> <p> <pre><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> <code>IsOdd</code> is simply the Boolean negation of <code>IsEven</code>. Like <code>IsEven</code> it also works correctly: </p> <p> <pre>&gt; <span style="color:#2b91af;">NaturalNumber</span>.Six.IsOdd().Match(trueCase:&nbsp;<span style="color:#a31515;">&quot;Odd&quot;</span>,&nbsp;falseCase:&nbsp;<span style="color:#a31515;">&quot;Even&quot;</span>) "Even" &gt; <span style="color:#2b91af;">NaturalNumber</span>.Seven.IsOdd().Match(trueCase:&nbsp;<span style="color:#a31515;">&quot;Odd&quot;</span>,&nbsp;falseCase:&nbsp;<span style="color:#a31515;">&quot;Even&quot;</span>) "Odd"</pre> </p> <p> You can implement other operators (like multiplication) and predicates from the building blocks shown here, but I'm not going to cover that here (see <a href="https://github.com/ploeh/ChurchEncoding/tree/a8512fe004dc7da41fa17b069a6c245c31b97d7c">the accompanying GitHub repository for more code</a>). I hope that this article gave you a sense of how a programming language can be designed from the low-level building blocks defined by the lambda calculus. </p> <h3 id="b4be8911648f4dcab6191fd50c03581a"> Summary <a href="#b4be8911648f4dcab6191fd50c03581a" title="permalink">#</a> </h3> <p> <a href="https://en.wikipedia.org/wiki/Giuseppe_Peano">Giuseppe Peano</a> described natural numbers as an initial number (zero) and successors to that number. Church formulated Peano numbers in the lambda calculus. Using Church encoding, you can translate this representation to various programming languages, including, as you've seen in this article, C#. </p> <p> In the previous article, you saw how to model Boolean values as a set of functions with two arguments. In this article, you saw how to model natural numbers with another set of functions that take two arguments. In the next article, you'll see another data type modelled as a set of functions with two arguments. It looks like a patterns is starting to appear. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/06/04/church-encoded-maybe">Church-encoded Maybe</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Church-encoded Boolean values http://blog.ploeh.dk/2018/05/24/church-encoded-boolean-values 2018-05-24T04:49:00+00:00 Mark Seemann <div id="post"> <p> <em>Boolean values, and logical branching, don't have to be built into programming languages. An introduction for object-oriented programmers.</em> </p> <p> This article is part of <a href="http://blog.ploeh.dk/2018/05/22/church-encoding">a series of articles about Church encoding</a>. </p> <p> Years ago, the so-called <a href="http://www.antiifcampaign.com">Anti-IF Campaign</a> made the rounds on various social media (back then, IIRC, mostly known as 'the blogosphere'). The purpose of the campaign was never to eradicate every single use of <code>if</code> statements or expressions in source code, but rather to educate people about alternatives to the <a href="http://wiki.c2.com/?ArrowAntiPattern">Arrow anti-pattern</a>. </p> <p> One easy way to deal with arrow code is to <a href="https://refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html">Replace Nested Conditionals with Guard Clauses</a>, but that's not always possible. Another way is to encapsulate some <code>if</code> blocks in helper methods. Yet another way would be to use polymorphic dispatch, but how does that even work? Don't you, deep down, need at least a few <code>if</code> keywords here and there? </p> <p> It turns out that the answer, surprisingly, is <em>no</em>. </p> <h3 id="3215aad4142e466393c8a533e4bda305"> Untyped Boolean functions <a href="#3215aad4142e466393c8a533e4bda305" title="permalink">#</a> </h3> <p> <code>if/then/else</code> expressions are based on Boolean values (<em>true</em> and <em>false</em>): if some Boolean value is true, then something happens; otherwise, something else happens. Most programming languages, including C, C++, Java, C#, and JavaScript, have a <a href="https://en.wikipedia.org/wiki/%3F:">ternary operator</a>, which in C# looks like this: </p> <p> <pre>isEven&nbsp;?&nbsp;<span style="color:#a31515;">&quot;Probably&nbsp;not&nbsp;a&nbsp;prime.&quot;</span>&nbsp;:&nbsp;<span style="color:#a31515;">&quot;Could&nbsp;be&nbsp;a&nbsp;prime.&quot;</span>;</pre> </p> <p> You can think of an expression like that as a function that takes a Boolean value and two potential return values: one for the <em>true</em> case, and one for the <em>false</em> case. </p> <p> In <a href="https://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a>, the only primitive building blocks are functions. There's no built-in Boolean values, but you can define them with functions. Boolean values are functions that take two arguments. By conventions, the first argument (the one to the left) represents the <em>true</em> case, whereas the second argument (to the right) signifies the <em>false</em> case - just like the ternary operator. In the lambda calculus, functions are curried, but we know from <a href="http://blog.ploeh.dk/2018/02/05/uncurry-isomorphisms">uncurry isomorphisms</a> that we can also represent a two-argument function as a function that takes a two-tuple (a <em>pair</em>) as a single argument. Furthermore, we know from <a href="http://blog.ploeh.dk/2018/01/22/function-isomorphisms">function isomorphisms</a> that we can represent a function as an instance method. Therefore, we can declare a Boolean value in C# to be an object that implements this interface: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IChurchBoolean</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">object</span>&nbsp;Match(<span style="color:blue;">object</span>&nbsp;trueCase,&nbsp;<span style="color:blue;">object</span>&nbsp;falseCase); }</pre> </p> <p> You'll notice that I've chosen to call the method <code>Match</code>, for reasons that should hopefully become clear as we go along. </p> <p> The intent with such a Church-encoded Boolean is that any object that represents <em>true</em> should return the left argument (<code>trueCase</code>), whereas an object that represents <em>false</em> should return the right argument (<code>falseCase</code>). </p> <p> In other words, <em>true</em> is an interface implementation: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IChurchBoolean</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">object</span>&nbsp;Match(<span style="color:blue;">object</span>&nbsp;trueCase,&nbsp;<span style="color:blue;">object</span>&nbsp;falseCase) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;trueCase; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Notice that this implementation always returns <code>trueCase</code> while ignoring <code>falseCase</code>. No explicit <code>if</code> statement is required. </p> <p> Likewise, <em>false</em> is implemented the same way: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IChurchBoolean</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">object</span>&nbsp;Match(<span style="color:blue;">object</span>&nbsp;trueCase,&nbsp;<span style="color:blue;">object</span>&nbsp;falseCase) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;falseCase; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> So far, this doesn't offer much capability, but it does already give you the ability to choose between two values, as this little C# Interactive session demonstrates: </p> <p> <pre>&gt; var b = new ChurchTrue(); &gt; b.Match("foo", "bar") "foo" &gt; var b = new ChurchFalse(); &gt; b.Match("foo", "bar") "bar"</pre> </p> <p> When 'the Boolean value' is a <code>ChurchTrue</code> instance, then the left argument is returned; otherwise, when <code>b</code> is a <code>ChurchFalse</code> object, the return value is the right-hand value - just like the ternary operator. </p> <h3 id="1ebf901dbc234074a98b809ebeb570b1"> Boolean And <a href="#1ebf901dbc234074a98b809ebeb570b1" title="permalink">#</a> </h3> <p> You can now define the standard Boolean operators <em>and</em>, <em>or</em>, and <em>not</em>. Starting with <em>and:</em> </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">ChurchAnd</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IChurchBoolean</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;y; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;ChurchAnd(<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;x,&nbsp;<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;y) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.x&nbsp;=&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.y&nbsp;=&nbsp;y; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">object</span>&nbsp;Match(<span style="color:blue;">object</span>&nbsp;trueCase,&nbsp;<span style="color:blue;">object</span>&nbsp;falseCase) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;x.Match(y.Match(trueCase,&nbsp;falseCase),&nbsp;falseCase); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> The <code>ChurchAnd</code> class is an implementation of <code>IChurchBoolean</code> that composes two other <code>IChurchBoolean</code> values, <code>x</code> and <code>y</code>. You can use it like this: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;b&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchAnd</span>(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>(),&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>()); </pre> </p> <p> In this case, <code>b</code> represents <em>false</em>, because it'll always return the right-hand argument when <code>Match</code> is invoked. </p> <p> Notice that the implementation of <code>ChurchAnd.Match</code> first matches on <code>x</code>. Only if <code>x</code> itself is <em>true</em> can the expression passed as the first argument be returned; otherwise, <code>falseCase</code> will be returned. Thus, if <code>x</code> is <em>true</em>, the expression <code>y.Match(trueCase, falseCase)</code> will be returned, and only if that as well evaluates to <em>true</em> is the final result <em>true</em>. The <code>trueCase</code> value is only returned if <code>y</code> represents <em>true</em>, as well as <code>x</code>. </p> <p> In the lambda calculus, Boolean <em>and</em> is defined like this: </p> <p> <pre>and = λx.λy.λt.λf.x (y t f) f</pre> </p> <p> The way to read this is that Boolean <em>and</em> is a function that takes four arguments: <ul> <li><code>x</code>, a Boolean value</li> <li><code>y</code>, another Boolean value</li> <li><code>t</code>, the value to return if the expression is <em>true</em>; the <code>trueCase</code> argument in the above C# implementation.</li> <li><code>f</code>, the value to return if the expression is <em>false</em>; the <code>falseCase</code> argument in the above C# implementation.</li> </ul> Recall that in the lambda calculus, Boolean values are functions that take two arguments, so <code>x</code> and <code>y</code> are functions. <code>and</code> calls <code>x</code> with two arguments. Since Boolean <em>and</em> requires both <code>x</code> and <code>y</code> to be <em>true</em>, it passes <code>f</code> as the second argument to <code>x</code>, because if <code>x</code> represents <em>false</em>, it'll return its right-hand argument. Only if <code>x</code> represents <em>true</em> does it make sense to investigate the Boolean value of <code>y</code>, which is also a function that takes two arguments. Only if <code>y</code> also represents <em>true</em> will <code>t</code> be returned. </p> <p> This is exactly the same implementation as the above C# code. </p> <p> Wait a minute, though, didn't I write that Boolean values are functions that take two arguments? And isn't <code>and</code> a function that takes four arguments? </p> <p> Yes, indeed. That's how currying works. You can view <code>and</code> as a function that takes four arguments, but you can also view it as a function that takes two arguments (<code>x</code> and <code>y</code>) and returns another function that takes two arguments. This becomes clearer with partial application. When translating to C#, the 'contract' (that a Boolean value is a function that takes two arguments) is modelled as the interface <code>IChurchBoolean</code>, while the 'extra arguments' <code>x</code> and <code>y</code> become class fields, injected via the class' constructor. </p> <h3 id="33ba3de3f9bd46fabbc0b44935578c15"> Boolean Or <a href="#33ba3de3f9bd46fabbc0b44935578c15" title="permalink">#</a> </h3> <p> In the lambda calculus, Boolean <em>or</em> is defined like this: </p> <p> <pre>or = λx.λy.λt.λf.x t (y t f)</pre> </p> <p> Translated to C#, this becomes: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">ChurchOr</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IChurchBoolean</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;y; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;ChurchOr(<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;x,&nbsp;<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;y) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.x&nbsp;=&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.y&nbsp;=&nbsp;y; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">object</span>&nbsp;Match(<span style="color:blue;">object</span>&nbsp;trueCase,&nbsp;<span style="color:blue;">object</span>&nbsp;falseCase) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;x.Match(trueCase,&nbsp;y.Match(trueCase,&nbsp;falseCase)); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> You can see that this is another direct translation. Boolean <em>or</em> only requires (at least) one of the Boolean values to be <em>true</em>, so if <code>x</code> is <em>true</em>, you can immediately return <code>trueCase</code>. Otherwise, in the case where <code>x</code> is <em>false</em>, there's still a chance that the entire expression could be <em>true</em>, so you'll have to evaluate <code>y</code> as well. When <code>y</code> represents <em>true</em>, you can still return <code>trueCase</code>. Only when <code>y</code> is also <em>false</em> should you return <code>falseCase</code>. </p> <p> You can use <code>ChurchOr</code> like this: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;b&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchOr</span>(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>(),&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>()); </pre> </p> <p> Here, <code>b</code> is <em>true</em> because <em>true or false</em> is <em>true</em>. </p> <h3 id="3238c67454fe4463946b9625c447571a"> Boolean Not <a href="#3238c67454fe4463946b9625c447571a" title="permalink">#</a> </h3> <p> Finally, you can also define Boolean negation. In lambda calculus it's: </p> <p> <pre>not = λx.λt.λf.x f t</pre> </p> <p> Notice how this simply swaps the arguments passed to <code>x</code>. In C#, this translates to: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">ChurchNot</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IChurchBoolean</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;b; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;ChurchNot(<span style="color:#2b91af;">IChurchBoolean</span>&nbsp;b) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.b&nbsp;=&nbsp;b; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">object</span>&nbsp;Match(<span style="color:blue;">object</span>&nbsp;trueCase,&nbsp;<span style="color:blue;">object</span>&nbsp;falseCase) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;b.Match(falseCase,&nbsp;trueCase); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> You can combine all the Boolean operators like this: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;b&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchOr</span>(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchFalse</span>(),&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchNot</span>(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ChurchTrue</span>())); </pre> </p> <p> Here, <code>b</code> is <em>false</em> because <em>false or (not true)</em> is <em>false</em>. </p> <h3 id="5a06c7f9d7b04b31a8f4ca6ab9b28ca4"> Typed Boolean functions <a href="#5a06c7f9d7b04b31a8f4ca6ab9b28ca4" title="permalink">#</a> </h3> <p> So far, the <code>IChurchBoolean</code> interface has been untyped, in the sense that it took <code>object</code> arguments and had an <code>object</code> return type. You can, however, easily make the interface strongly typed, using generics: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IChurchBoolean</span> { &nbsp;&nbsp;&nbsp;&nbsp;<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 doesn't really change the rest of the code you've seen in this article. The method signatures chance, but the implementations remain as shown. You can see the change in <a href="https://github.com/ploeh/ChurchEncoding/commit/2cba6d7625b08054caf6f42cc30898ced704848f">this commit</a>. </p> <h3 id="9821112728f64424b39990eb26ede2b8"> Semigroups and monoids <a href="#9821112728f64424b39990eb26ede2b8" title="permalink">#</a> </h3> <p> The strongly typed signature accentuates that the <code>Match</code> method is a binary operation; it takes two values of the type <code>T</code> and returns a single <code>T</code> value. Is it a <a href="http://blog.ploeh.dk/2017/10/06/monoids">monoid</a>, then? </p> <p> It's not a single monoid, but rather a collection of <a href="http://blog.ploeh.dk/2017/11/27/semigroups">semigroups</a>, some of which are monoids as well. The implementation of <code>ChurchTrue</code> corresponds to the <em>first</em> semigroup, and <code>ChurchFalse</code> to the <em>last</em> semigroup. You can make this explict in <a href="https://www.haskell.org">Haskell</a>: </p> <p> <pre><span style="color:blue;">import</span>&nbsp;Data.Semigroup <span style="color:#2b91af;">churchTrue</span>&nbsp;::&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a churchTrue&nbsp;t&nbsp;f&nbsp;=&nbsp;getFirst&nbsp;(First&nbsp;t&nbsp;&lt;&gt;&nbsp;First&nbsp;f)</pre> </p> <p> If you compare this implementation of <code>churchTrue</code> to the <a href="http://programmable.computer/posts/church_encoding.html">Travis Whitaker's <code>true</code> function</a>, his is much simpler. I'm not suggesting that using <code>First</code> is better; I'm only trying to illustrate the connection. </p> <p> If you aren't familiar with how things are done in Haskell, <code>&lt;&gt;</code> is the 'generic semigroup binary operator'. What it does depends on the type of expressions surrounding it. By wrapping both <code>t</code> and <code>f</code> in <code>First</code> containers, the <code>&lt;&gt;</code> operator becomes the operator that always returns the first argument (i.e. <code>First t</code>). Since the result is a <code>First</code> value, you have to unwrap it again by applying <code>getFirst</code>. </p> <p> Likewise, you can define <em>false:</em> </p> <p> <pre><span style="color:#2b91af;">churchFalse</span>&nbsp;::&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a churchFalse&nbsp;t&nbsp;f&nbsp;=&nbsp;getLast&nbsp;(Last&nbsp;t&nbsp;&lt;&gt;&nbsp;Last&nbsp;f)</pre> </p> <p> This still uses the <code>&lt;&gt;</code> operator, but now with the <code>Last</code> container, which gives it all the behaviour of the <em>last</em> semigroup. </p> <p> The <em>any</em> and <em>all</em> monoids are implemented as compositions of these two fundamental semigroups. In the C# code in this article, they're implemented by <code>ChurchAnd</code> and <code>ChurchOr</code>, although in neither case have I defined an explicit identity value. This is, however, possible, so let's continue with the Haskell code to see what that would look like. First, you can define the 'naked' operations: </p> <p> <pre>churchAnd&nbsp;x&nbsp;y&nbsp;t&nbsp;f&nbsp;=&nbsp;x&nbsp;(y&nbsp;t&nbsp;f)&nbsp;f churchOr&nbsp;x&nbsp;y&nbsp;t&nbsp;f&nbsp;=&nbsp;x&nbsp;t&nbsp;(y&nbsp;t&nbsp;f)</pre> </p> <p> I have here omitted the type signatures on purpose, as I believe they might confuse rather than help. In both cases, the logic is the same as in the above <code>ChurchAnd</code> and <code>ChurchOr</code> classes, although, as you can see, Haskell code is much terser. </p> <p> These two functions already work as desired, but we can easily turn both into their respective monoids. First, the <em>all</em> monoid: </p> <p> <pre><span style="color:blue;">newtype</span>&nbsp;ChurchAll&nbsp;=&nbsp;ChurchAll&nbsp;{&nbsp;runAll&nbsp;::&nbsp;forall&nbsp;a.&nbsp;a&nbsp;-&gt;&nbsp;a&nbsp;-&gt;&nbsp;a&nbsp;} <span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Semigroup</span>&nbsp;<span style="color:blue;">ChurchAll</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;&nbsp;&nbsp;ChurchAll&nbsp;x&nbsp;&lt;&gt;&nbsp;ChurchAll&nbsp;y&nbsp;=&nbsp;ChurchAll&nbsp;(churchAnd&nbsp;x&nbsp;y) <span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Monoid</span>&nbsp;<span style="color:blue;">ChurchAll</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;&nbsp;&nbsp;mempty&nbsp;=&nbsp;ChurchAll&nbsp;churchTrue &nbsp;&nbsp;&nbsp;&nbsp;mappend&nbsp;=&nbsp;<span style="color:#2b91af;">(&lt;&gt;)</span></pre> </p> <p> In order for this code to compile, you must enable the <em>RankNTypes</em> language extension, which I did by adding the <code>{-# LANGUAGE RankNTypes #-}</code> pragma to the top of my code file. The <code>forall a</code> declaration corresponds to the <code>&lt;T&gt;</code> type annotation on the C# <code>Match</code> method. You can think of this as that the type argument is scoped to the function instead of the type. </p> <p> The <code>Semigroup</code> instance simply delegates its behaviour to <code>churchAnd</code>, and the <code>Monoid</code> instance returns <code>churchTrue</code> as the identity (<code>mempty</code>). </p> <p> Similarly, you can implement the <em>any</em> monoid: </p> <p> <pre><span style="color:blue;">newtype</span>&nbsp;ChurchAny&nbsp;=&nbsp;ChurchAny&nbsp;{&nbsp;runAny&nbsp;::&nbsp;forall&nbsp;a.&nbsp;a&nbsp;-&gt;&nbsp;a&nbsp;-&gt;&nbsp;a&nbsp;} <span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Semigroup</span>&nbsp;<span style="color:blue;">ChurchAny</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;&nbsp;&nbsp;ChurchAny&nbsp;x&nbsp;&lt;&gt;&nbsp;ChurchAny&nbsp;y&nbsp;=&nbsp;ChurchAny&nbsp;(churchOr&nbsp;x&nbsp;y) <span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Monoid</span>&nbsp;<span style="color:blue;">ChurchAny</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;&nbsp;&nbsp;mempty&nbsp;=&nbsp;ChurchAny&nbsp;churchFalse &nbsp;&nbsp;&nbsp;&nbsp;mappend&nbsp;=&nbsp;<span style="color:#2b91af;">(&lt;&gt;)</span></pre> </p> <p> As is also the case with <code>ChurchAll</code>, the <code>ChurchAny</code> instance of <code>Semigroup</code> simply delegates to a 'naked' function (in this case <code>churchOr</code>), and the <code>Monoid</code> instance again delegates <code>mappend</code> to <code>&lt;&gt;</code> and returns <code>churchFalse</code> as the identity. </p> <p> The following brief GHCi session demonstrates that it all works as intended: </p> <p> <pre>λ&gt; runAny (ChurchAny churchTrue &lt;&gt; ChurchAny churchFalse) "foo" "bar" "foo" λ&gt; runAny (ChurchAny churchFalse &lt;&gt; ChurchAny churchFalse) "foo" "bar" "bar" λ&gt; runAll (ChurchAll churchFalse &lt;&gt; ChurchAll churchTrue) "foo" "bar" "bar" λ&gt; runAll (ChurchAll churchTrue &lt;&gt; ChurchAll churchTrue) "foo" "bar" "foo"</pre> </p> <p> Recall that a Church-encoded Boolean is a function that takes two values - in all the four above examples <code>"foo"</code> and <code>"bar"</code>. When the expression represents <em>true</em> it returns the left-hand value (<code>"foo"</code>); otherwise, it returns the right-hand value (<code>"bar"</code>). </p> <p> In summary, the Church-encoded Boolean values <em>true</em> and <em>false</em> correspond to the <em>first</em> and <em>last</em> semigroups. You can compose the well-known monoids over Boolean values using these two basic building blocks. </p> <h3 id="b0ac2fd3255c4c61af0f6ddb4f95b365"> Summary <a href="#b0ac2fd3255c4c61af0f6ddb4f95b365" title="permalink">#</a> </h3> <p> You'd normally think of Boolean values as language primitives. <em>True</em> and <em>false</em> are built into most languages, as well as common operators like <em>and</em>, <em>or</em>, and <em>not</em>. While this is convenient, it doesn't <em>have</em> to be like this. Even in languages that already have built-in support for Boolean values, like Haskell or C#, you can define Church-encoded Boolean values from first principles. </p> <p> In the lambda calculus, a Boolean value is function that takes two arguments and returns the left-hand argument when <em>true</em>, and the right-hand argument when <em>false</em>. </p> <p> At this point, it may seem like you can't do much with the <code>IChurchBoolean</code> API. How could you, for instance, determine whether an integer is even or odd? </p> <p> This innocuous-looking question is harder to answer than you may think, so that's worthy of its own article. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/05/28/church-encoded-natural-numbers">Church-encoded natural numbers</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Church encoding http://blog.ploeh.dk/2018/05/22/church-encoding 2018-05-22T06:28:00+00:00 Mark Seemann <div id="post"> <p> <em>Church encoding is a unified way to model data and functions. An introduction for object-oriented developers.</em> </p> <p> This article series is part of <a href="http://blog.ploeh.dk/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> </p> <p> When asked why I like functional programming so much, I often emphasise the <a href="http://blog.ploeh.dk/2016/02/10/types-properties-software-designing-with-types">superior modelling ability</a> that I get from <a href="https://en.wikipedia.org/wiki/Algebraic_data_type">algebraic data types</a>. Particularly, languages like <a href="http://fsharp.org">F#</a> and <a href="https://www.haskell.org">Haskell</a> have <a href="https://en.wikipedia.org/wiki/Tagged_union">sum types</a> in addition to the <a href="https://en.wikipedia.org/wiki/Product_type">product types</a> that most statically typed languages seem to have. </p> <p> In short, a <em>sum type</em> gives you the ability to declare, as part of the type system, that a particular data type must be exactly one of a <em>finite</em> list of mutually exclusive options. This differs from common object-oriented sub-typing because class inheritance or interface implementation offers conceptually infinite extensibility. Sometimes, unconstrained extensibility is exactly what you need, but in other cases, the ability to define a closed set of cases can be an effective modelling tool. If you need an easy-to-read introduction to algebraic data types, I recommend <a href="http://tomasp.net">Tomas Petricek</a>'s fine article <a href="http://tomasp.net/blog/types-and-math.aspx">Power of mathematics: Reasoning about functional types</a>. </p> <p> Interestingly, <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html">TypeScript has sum types</a>, so they don't have to belong exclusively in the realm of functional programming. In this article series, you'll see an alternative way to represent sum types in C# using <em>Church encoding</em>. </p> <h3 id="981c0967cd414784968a1ceded3f9f45"> Lambda calculus <a href="#981c0967cd414784968a1ceded3f9f45" title="permalink">#</a> </h3> <p> In the 1930s, several mathematicians were investigating the foundations of mathematics. One of them, <a href="https://en.wikipedia.org/wiki/Alonzo_Church">Alonzo Church</a>, developed <a href="https://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a> as a universal model of computation. In a sense, you can think of lambda calculus as a sort of hypothetical programming language, although it was never designed to be a practical programming language. Even so, you can learn a lot from it. </p> <p> In the untyped lambda calculus, the only primitive data type is a function. There are no primitive numbers, Boolean values, branching instructions, loops, or anything else you'd normally consider as parts of a programming language. Instead, there's only functions, written as <em>lambda expressions:</em> </p> <p> <pre>λf.λx.f x</pre> </p> <p> This looks opaque and mathematical, but most modern programmers should be familiar with lambda (λ) expressions. The above expression is an anonymous function that takes a single argument: <code>f</code>. The body of the function is the return value; here, another lambda expression: <code>λx.f x</code>. This lambda expression also takes a single argument: <code>x</code>. </p> <p> In the untyped lambda calculus, everything is a function, so that includes <code>f</code> and <code>x</code>. The return value of the entire expression is <code>f x</code>, which means that the function <code>f</code> is applied to the value (in fact: function) <code>x</code>. The entire expression is therefore a <a href="https://en.wikipedia.org/wiki/Higher-order_function">higher-order function</a>. </p> <p> In C#, the corresponding lambda expression would be: </p> <p> <pre>f =&gt; x =&gt; f(x)</pre> </p> <p> This is a lambda expression that returns another lambda expression, which again returns the result of calling the function <code>f</code> with the value <code>x</code>. </p> <p> In F#, it would be: </p> <p> <pre>fun f -&gt; fun x -&gt; f x</pre> </p> <p> and in Haskell, it would be: </p> <p> <pre>\f -&gt; \x -&gt; f x</pre> </p> <p> In both Haskell and F#, functions are already curried, so you can shorten that Haskell lambda expression to: </p> <p> <pre>\f x -&gt; f x</pre> </p> <p> and the F# lambda expression to: </p> <p> <pre>fun f x -&gt; f x</pre> </p> <p> This looks more like a function that takes two arguments, so alternatively, via <a href="http://blog.ploeh.dk/2018/02/05/uncurry-isomorphisms">uncurry isomorphisms</a>, you can also write the C# representation like this: </p> <p> <pre>(f, x) =&gt; f(x)</pre> </p> <p> Those six lambda expressions, however, are statically typed, even though they're generic (or, as Haskellers would put it, <a href="https://en.wikipedia.org/wiki/Parametric_polymorphism">parametric polymorphic</a>). This means that they're not entirely equal to <code>λf.λx.f x</code>, but it should give you a sense of what a lambda expression is. </p> <p> It turns out that using nothing but lambda expressions, one can express any computation; lambda calculus is Turing-complete. </p> <h3 id="a921177fdc9e485389b476ab7f599aa7"> Church encoding <a href="#a921177fdc9e485389b476ab7f599aa7" title="permalink">#</a> </h3> <p> Since languages like C#, F#, Haskell, and others, include lambda expressions, you can reproduce as much of the lambda calculus as you'd like. In this article series, I'll mainly use it to show you how to represent sum types in C#. Later, you'll see how it relates to design patterns. </p> <p> <ul> <li><a href="http://blog.ploeh.dk/2018/05/24/church-encoded-boolean-values">Church-encoded Boolean values</a></li> <li><a href="http://blog.ploeh.dk/2018/05/28/church-encoded-natural-numbers">Church-encoded natural numbers</a></li> <li><a href="http://blog.ploeh.dk/2018/06/04/church-encoded-maybe">Church-encoded Maybe</a></li> <li><a href="http://blog.ploeh.dk/2018/06/11/church-encoded-either">Church-encoded Either</a></li> <li><a href="http://blog.ploeh.dk/2018/06/18/church-encoded-payment-types">Church-encoded payment types</a></li> </ul> </p> <p> These articles give you examples in C#. For Haskell examples, I found <a href="http://programmable.computer">Travis Whitaker</a>'s article <a href="http://programmable.computer/posts/church_encoding.html">Scrap Your Constructors: Church Encoding Algebraic Types</a> useful. </p> <p> All C# code for these articles is <a href="https://github.com/ploeh/ChurchEncoding">available on GitHub</a>. </p> <h3 id="36ea9ca3c38842ed906e2b02d175d116"> Summary <a href="#36ea9ca3c38842ed906e2b02d175d116" title="permalink">#</a> </h3> <p> You can use lambda expressions to define all sorts of data types and computations. Because lambda calculus is a universal model of computation, you can learn about fundamental representations of computation. Particularly, lambda calculus offers a model of logical branching, which again teaches us how to model sum types. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/05/24/church-encoded-boolean-values">Church-encoded Boolean values</a>. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="e42f37bb7e4440609b922f07211c591c"> <div class="comment-author"><a href="http://github.com/jamesfoster">James Foster</a></div> <div class="comment-content">Hey Mark, Just watched your Humane Code series so far on <a href="https://cleancoders.com">cleancoders.com</a>. Really enjoying it. Looking forward to the next episode with much anticipation!<br> <br> James</div> <div class="comment-date">2018-05-24 12:42 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Composite as a monoid - a business rules example http://blog.ploeh.dk/2018/05/17/composite-as-a-monoid---a-business-rules-example 2018-05-17T06:45:00+00:00 Mark Seemann <div id="post"> <p> <em>Composites are monoids. An example in C#, F#, and Haskell.</em> </p> <p> Towards the end of the first decade of the third millennium, I'd been writing object-oriented code for about ten years, and I'd started to notice some patterns in my code. I'd read <a href="http://amzn.to/XBYukB">Design Patterns</a> 6-7 years earlier, but I noticed that I tended to use only a small subset of the patterns from the book - particularly <a href="https://en.wikipedia.org/wiki/Composite_pattern">Composite</a>, <a href="https://en.wikipedia.org/wiki/Decorator_pattern">Decorator</a>, <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">Chain of Responsibility</a>, and a few others. </p> <p> In particular, I noticed that modelling seemed to be easier, and the code better structured, when I could apply the Composite design pattern. It was also clear, however, that I couldn't always use the Composite pattern, so I started to speculate on what could be the distinguishing factors. In 2010, I made <a href="http://blog.ploeh.dk/2010/12/03/Towardsbetterabstractions">a first attempt at identifying when a Composite is possible</a>, and when it isn't. Unfortunately, while it was a fine attempt (which I'll return to later), it didn't lead anywhere. Ultimately, I gave up on the subject and moved on to other things. </p> <h3 id="84b7af9ddccf4ea7a113f356039d582d"> A revelation <a href="#84b7af9ddccf4ea7a113f356039d582d" title="permalink">#</a> </h3> <p> One of my interests in the next decade became functional programming. One day in late 2016 I came across <a href="https://codereview.stackexchange.com/q/149559/3878">this Code Review question</a> by <a href="https://bizmonger.wordpress.com">Scott Nimrod</a>. It was an solution to <a href="http://codekata.com/kata/kata16-business-rules">the Business Rules kata</a>, which, briefly told, is about implementing changing business rules in a sustainable manner. </p> <p> In my answer to the question, I gave an outline (repeated below) of how I would address the problem in <a href="http://fsharp.org">F#</a>. As a comment to my answer, Scott wrote: </p> <p> "Feels like the Decorator Pattern..." </p> <p> I responded, </p> <p> "Not really; it's the Composite pattern..." </p> <p> A few days later, as I was doing something else, it suddenly dawned on me that not only was a few lines of F# code equivalent to the Composite design pattern, but those lines of code were also manifestations of fundamental abstractions from <a href="https://en.wikipedia.org/wiki/Category_theory">category theory</a>. Originally, I thought Composite was a combination of applicative functors and <a href="http://blog.ploeh.dk/2017/10/06/monoids">monoids</a>, but as I investigated, I discovered that <a href="http://blog.ploeh.dk/2018/03/12/composite-as-a-monoid">Composites are simply monoids</a>. </p> <p> This article shows a concrete example of that discovery, starting with my original F# code, subsequently translating it to C# to demonstrate that it's a Composite, and concluding with a translation to <a href="https://www.haskell.org">Haskell</a> in order to demonstrate that it all fits with the formalisation of <code>Monoid</code> there. </p> <h3 id="b2833023b804484db532f3626bad6b0c"> Original F# solution outline <a href="#b2833023b804484db532f3626bad6b0c" title="permalink">#</a> </h3> <p> The kata is about modelling volatile business rules in a sustainable manner. Particularly, you must implement various business rules associated with payments for products and services. Making a rough outline of a model, I started by introducing some types in F#: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;Membership&nbsp;=&nbsp;Basic&nbsp;|&nbsp;Gold <span style="color:blue;">type</span>&nbsp;Good&nbsp;= |&nbsp;PhysicalProduct&nbsp;<span style="color:blue;">of</span>&nbsp;string |&nbsp;Book&nbsp;<span style="color:blue;">of</span>&nbsp;string |&nbsp;Video&nbsp;<span style="color:blue;">of</span>&nbsp;string |&nbsp;Membership&nbsp;<span style="color:blue;">of</span>&nbsp;Membership |&nbsp;Upgrade <span style="color:blue;">type</span>&nbsp;Command&nbsp;= |&nbsp;Slip&nbsp;<span style="color:blue;">of</span>&nbsp;string&nbsp;*&nbsp;(Good&nbsp;list) |&nbsp;Activate&nbsp;<span style="color:blue;">of</span>&nbsp;Membership |&nbsp;Upgrade |&nbsp;PayAgent</pre> </p> <p> This basically states that there's a closed hierarchy of goods, and a closed hierarchy of business commands, as well as a <code>Membership</code> enumeration. A <em>good</em> can be a physical product with a name, a book with a name, a membership or upgrade, and so on. A <em>command</em> can be a packing slip, a membership activation, and so on. </p> <p> Since I was only interested in a rough outline of a solution, I only sketched four business rules, all implemented as functions. The first creates a packing slip for certain goods: </p> <p> <pre><span style="color:green;">//&nbsp;Good&nbsp;-&gt;&nbsp;Command&nbsp;list</span> <span style="color:blue;">let</span>&nbsp;slipForShipping&nbsp;=&nbsp;<span style="color:blue;">function</span> |&nbsp;PhysicalProduct&nbsp;name&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[Slip&nbsp;(<span style="color:#a31515;">&quot;Shipping&quot;</span>,&nbsp;[PhysicalProduct&nbsp;name])] |&nbsp;Book&nbsp;name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[Slip&nbsp;(<span style="color:#a31515;">&quot;Shipping&quot;</span>,&nbsp;[Book&nbsp;name])] |&nbsp;Video&nbsp;name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[Slip&nbsp;(<span style="color:#a31515;">&quot;Shipping&quot;</span>,&nbsp;[Video&nbsp;name])] |&nbsp;_&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[]</pre> </p> <p> This function takes a <code>Good</code> value as input and returns a list of <code>Command</code> values as output. If the <code>Good</code> is a <code>PhysicalProduct</code>, <code>Book</code>, or <code>Video</code>, it returns a packing slip command; otherwise, it returns an empty list of commands. </p> <p> The next business rule is a similar function: </p> <p> <pre><span style="color:green;">//&nbsp;Good&nbsp;-&gt;&nbsp;Command&nbsp;list</span> <span style="color:blue;">let</span>&nbsp;slipForRoyalty&nbsp;=&nbsp;<span style="color:blue;">function</span> |&nbsp;Book&nbsp;name&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[Slip&nbsp;(<span style="color:#a31515;">&quot;Royalty&quot;</span>,&nbsp;[Book&nbsp;name])] |&nbsp;_&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[]</pre> </p> <p> This business rule generates a royalty slip for any <code>Book</code>, but does nothing for any other <code>Good</code>. </p> <p> The third business rule activates a membership: </p> <p> <pre><span style="color:green;">//&nbsp;Good&nbsp;-&gt;&nbsp;Command&nbsp;list</span> <span style="color:blue;">let</span>&nbsp;activate&nbsp;=&nbsp;<span style="color:blue;">function</span>&nbsp;|&nbsp;Membership&nbsp;x&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[Activate&nbsp;x]&nbsp;|&nbsp;_&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[]</pre> </p> <p> If the <code>Good</code> is a <code>Membership</code>, the <code>activate</code> function returns a list containing a single <code>Activate</code> command; otherwise, it returns an empty list. </p> <p> Finally, the last rule upgrades a membership: </p> <p> <pre><span style="color:green;">//&nbsp;Good&nbsp;-&gt;&nbsp;Command&nbsp;list</span> <span style="color:blue;">let</span>&nbsp;upgrade&nbsp;=&nbsp;<span style="color:blue;">function</span>&nbsp;|&nbsp;Good.Upgrade&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[Upgrade]&nbsp;|&nbsp;_&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[]</pre> </p> <p> Similar to the previous functions, this one looks at the type of <code>Good</code>, and returns an <code>Upgrade</code> command when the input is an <code>Upgrade</code> good, and an empty list otherwise. </p> <p> Notice that all four functions share the same type: <code>Good -&gt; Command list</code>. I designed them like that on purpose, because this enables you to compose a list of business rules to a function that looks like a single rule: </p> <p> <pre><span style="color:green;">//&nbsp;(&#39;a&nbsp;-&gt;&nbsp;&#39;b&nbsp;list)&nbsp;list&nbsp;-&gt;&nbsp;&#39;a&nbsp;-&gt;&nbsp;&#39;b&nbsp;list</span> <span style="color:blue;">let</span>&nbsp;handle&nbsp;rules&nbsp;good&nbsp;=&nbsp;List.collect&nbsp;(<span style="color:blue;">fun</span>&nbsp;r&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;r&nbsp;good)&nbsp;rules</pre> </p> <p> This <code>handle</code> function takes a list of business rules (<code>rules</code>) and returns a new function with the type <code>Good -&gt; Command list</code> (or, actually, a function with the type <code>'a -&gt; 'b list</code> - once again I've fallen into the trap of <a href="http://blog.ploeh.dk/2015/08/17/when-x-y-and-z-are-great-variable-names">using too descriptive names</a>). Notice that this is the same type as the individual rules. </p> <p> You can now compose the four specific business rules: </p> <p> <pre><span style="color:green;">//&nbsp;Good&nbsp;-&gt;&nbsp;Command&nbsp;list</span> <span style="color:blue;">let</span>&nbsp;handleAll&nbsp;=&nbsp;handle&nbsp;[slipForShipping;&nbsp;slipForRoyalty;&nbsp;activate;&nbsp;upgrade]</pre> </p> <p> This function also has the type <code>Good -&gt; Command list</code> although it's a composition of four rules. </p> <p> You can use it like this <em>F# Interactive</em> example: </p> <p> <pre>&gt; handleAll (Book "The Annotated Turing");; val it : Command list = [Slip ("Shipping",[Book "The Annotated Turing"]); Slip ("Royalty",[Book "The Annotated Turing"])]</pre> </p> <p> (Yes, I like <a href="http://amzn.to/2n9MFGh">The Annotated Turing</a> - read <a href="https://www.goodreads.com/review/show/1731926050">my review on Goodreads</a>.) </p> <p> Notice that while each of the business rules produces only zero or one <code>Command</code> values, in this example <code>handleAll</code> returns two <code>Command</code> values. </p> <p> This design, where a composition looks like the things it composes, sounds familiar. </p> <h3 id="3d1128189a4a4e6ebbb5b1358e85a11f"> Business rules in C# <a href="#3d1128189a4a4e6ebbb5b1358e85a11f" title="permalink">#</a> </h3> <p> You can translate the above F# model to an object-oriented model in C#. Translating <a href="https://en.wikipedia.org/wiki/Tagged_union">discriminated unions</a> like <code>Good</code> and <code>Command</code> to C# always involves compromises. In order to keep the example as simple as possible, I decided to translate each of those to a <a href="https://en.wikipedia.org/wiki/Marker_interface_pattern">marker interface</a>, although I loathe that 'pattern': </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IGood</span>&nbsp;{&nbsp;}</pre> </p> <p> While the interface doesn't afford any behaviour, various classes can still implement it, like, for example, <code>Book</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Book</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IGood</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Book(<span style="color:blue;">string</span>&nbsp;name) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;=&nbsp;name; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">string</span>&nbsp;Name&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} }</pre> </p> <p> Other <code>IGood</code> 'implementations' looks similar, and there's a comparable class hierarchy for <code>ICommand</code>, which is another marker interface. </p> <p> The above F# code used a shared function type of <code>Good -&gt; Command list</code> as a polymorphic type for a business rule. You can <a href="http://blog.ploeh.dk/2018/01/08/software-design-isomorphisms">translate that to a C# interface</a>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IRule</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">ICommand</span>&gt;&nbsp;Handle(<span style="color:#2b91af;">IGood</span>&nbsp;good); }</pre> </p> <p> The above <code>slipForShipping</code> function becomes a class that implements the <code>IRule</code> interface: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">SlipForShippingRule</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IRule</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">ICommand</span>&gt;&nbsp;Handle(<span style="color:#2b91af;">IGood</span>&nbsp;good) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(good&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:#2b91af;">PhysicalProduct</span>&nbsp;|| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;good&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:#2b91af;">Book</span>&nbsp;|| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;good&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:#2b91af;">Video</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SlipCommand</span>(<span style="color:#a31515;">&quot;Shipping&quot;</span>,&nbsp;good)&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ICommand</span>[0]; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Instead of pattern matching on a discriminated union, the <code>Handle</code> method examines the subtype of <code>good</code> and only returns a <code>SlipCommand</code> if the <code>good</code> is either a <code>PhysicalProduct</code>, a <code>Book</code>, or a <code>Video</code>. </p> <p> The other implementations are similar, so I'm not going to show all of them, but here's one more: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">ActivateRule</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IRule</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">ICommand</span>&gt;&nbsp;Handle(<span style="color:#2b91af;">IGood</span>&nbsp;good) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;m&nbsp;=&nbsp;good&nbsp;<span style="color:blue;">as</span>&nbsp;<span style="color:#2b91af;">MembershipGood</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(m&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:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ActivateCommand</span>(m.Membership)&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ICommand</span>[0]; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Since 'all' members of <code>IRule</code> return <a href="http://blog.ploeh.dk/2017/10/10/strings-lists-and-sequences-as-a-monoid">collections, which form monoids over concatenation</a>, the interface itself gives rise to a monoid. This means that you can create a Composite: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">CompositeRule</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IRule</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">IRule</span>[]&nbsp;rules; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;CompositeRule(<span style="color:blue;">params</span>&nbsp;<span style="color:#2b91af;">IRule</span>[]&nbsp;rules) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.rules&nbsp;=&nbsp;rules; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">ICommand</span>&gt;&nbsp;Handle(<span style="color:#2b91af;">IGood</span>&nbsp;good) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;commands&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">ICommand</span>&gt;(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">foreach</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;rule&nbsp;<span style="color:blue;">in</span>&nbsp;rules) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;commands.AddRange(rule.Handle(good)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;commands; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Notice how the implementation of <code>Handle</code> follows the <a href="http://blog.ploeh.dk/2017/11/20/monoids-accumulate">template for monoid accumulation</a>. It starts with the <em>identity</em>, which, for the collection concatenation monoid is the empty collection. It then loops through all the composed <code>rules</code> and updates the accumulator <code>commands</code> in each iteration. Here, I used <code>AddRange</code>, which mutates <code>commands</code> instead of returning a new value, but the result is the same. Finally, the method returns the accumulator. </p> <p> You can now compose all the business rules and use the composition as though it was a single object: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;rule&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">CompositeRule</span>( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SlipForShippingRule</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">SlipForRoyaltyRule</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ActivateRule</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">UpgradeRule</span>()); <span style="color:blue;">var</span>&nbsp;book&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Book</span>(<span style="color:#a31515;">&quot;The&nbsp;Annotated&nbsp;Turing&quot;</span>); <span style="color:blue;">var</span>&nbsp;commands&nbsp;=&nbsp;rule.Handle(book);</pre> </p> <p> When the method returns, <code>commands</code> contains two <code>SlipCommand</code> objects - a packing slip, and a royalty slip. </p> <h3 id="e890108dc2534b97a57a843f60e5a01f"> Business rules in Haskell <a href="#e890108dc2534b97a57a843f60e5a01f" title="permalink">#</a> </h3> <p> You can also port the F# code to Haskell, which is usually easy as long as the F# is written in a 'functional style'. Since Haskell has an explicit notion of monoids, you'll be able to see how the two above solutions are monoidal. </p> <p> The data types are easy to translate to Haskell - you only have to adjust the syntax a bit: </p> <p> <pre><span style="color:blue;">data</span>&nbsp;Membership&nbsp;=&nbsp;Basic&nbsp;|&nbsp;Gold&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;">Enum</span>,&nbsp;<span style="color:#2b91af;">Bounded</span>) <span style="color:blue;">data</span>&nbsp;Good&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;PhysicalProduct&nbsp;String &nbsp;&nbsp;|&nbsp;Book&nbsp;String &nbsp;&nbsp;|&nbsp;Video&nbsp;String &nbsp;&nbsp;|&nbsp;Membership&nbsp;Membership &nbsp;&nbsp;|&nbsp;UpgradeGood &nbsp;&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#2b91af;">Show</span>,&nbsp;<span style="color:#2b91af;">Eq</span>) <span style="color:blue;">data</span>&nbsp;Command&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;Slip&nbsp;String&nbsp;[Good] &nbsp;&nbsp;|&nbsp;Activate&nbsp;Membership &nbsp;&nbsp;|&nbsp;Upgrade &nbsp;&nbsp;|&nbsp;PayAgent &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> The business rule functions are also easy to translate: </p> <p> <pre><span style="color:#2b91af;">slipForShipping</span>&nbsp;::&nbsp;<span style="color:blue;">Good</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[<span style="color:blue;">Command</span>] slipForShipping&nbsp;pp@(PhysicalProduct&nbsp;_)&nbsp;=&nbsp;[Slip&nbsp;<span style="color:#a31515;">&quot;Shipping&quot;</span>&nbsp;[pp]] slipForShipping&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;b@(Book&nbsp;_)&nbsp;=&nbsp;[Slip&nbsp;<span style="color:#a31515;">&quot;Shipping&quot;</span>&nbsp;&nbsp;[b]] slipForShipping&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;v@(Video&nbsp;_)&nbsp;=&nbsp;[Slip&nbsp;<span style="color:#a31515;">&quot;Shipping&quot;</span>&nbsp;&nbsp;[v]] slipForShipping&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_&nbsp;&nbsp;=&nbsp;<span style="color:blue;">[]</span> <span style="color:#2b91af;">slipForRoyalty</span>&nbsp;::&nbsp;<span style="color:blue;">Good</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[<span style="color:blue;">Command</span>] slipForRoyalty&nbsp;b@(Book&nbsp;_)&nbsp;=&nbsp;[Slip&nbsp;<span style="color:#a31515;">&quot;Royalty&quot;</span>&nbsp;[b]] slipForRoyalty&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_&nbsp;&nbsp;=&nbsp;<span style="color:blue;">[]</span> <span style="color:#2b91af;">activate</span>&nbsp;::&nbsp;<span style="color:blue;">Good</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[<span style="color:blue;">Command</span>] activate&nbsp;(Membership&nbsp;m)&nbsp;=&nbsp;[Activate&nbsp;m] activate&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_&nbsp;&nbsp;=&nbsp;<span style="color:blue;">[]</span> <span style="color:#2b91af;">upgrade</span>&nbsp;::&nbsp;<span style="color:blue;">Good</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[<span style="color:blue;">Command</span>] upgrade&nbsp;(UpgradeGood)&nbsp;=&nbsp;[Upgrade] upgrade&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_&nbsp;&nbsp;=&nbsp;<span style="color:blue;">[]</span></pre> </p> <p> Notice that all four business rules share the same type: <code>Good -&gt; [Command]</code>. This is conceptually the same type as in the F# code; instead of writing <code>Command list</code>, which is the F# syntax, the Haskell syntax for a list of <code>Command</code> values is <code>[Command]</code>. </p> <p> All those functions <a href="http://blog.ploeh.dk/2017/11/06/function-monoids">are monoids because their return types form a monoid</a>, so in Haskell, you can compose them without further ado: </p> <p> <pre><span style="color:#2b91af;">handleAll</span>&nbsp;::&nbsp;<span style="color:blue;">Good</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;[<span style="color:blue;">Command</span>] handleAll&nbsp;=&nbsp;mconcat&nbsp;[slipForShipping,&nbsp;slipForRoyalty,&nbsp;activate,&nbsp;upgrade]</pre> </p> <p> <code>mconcat</code> is a built-in function that aggregates any list of monoidal values to a single value: </p> <p> <pre>mconcat :: Monoid a =&gt; [a] -&gt; a</pre> </p> <p> Since all four functions are monoids, this just works out of the box. A Composite is just a monoid. Here's an example of using <code>handleAll</code> from GHCi: </p> <p> <pre>*BusinessRules&gt; handleAll $ Book "The Annotated Turing" [Slip "Shipping" [Book "The Annotated Turing"],Slip "Royalty" [Book "The Annotated Turing"]]</pre> </p> <p> The result is as you'd come to expect. </p> <p> Notice that not only don't you have to write a <code>CompositeRule</code> class, you don't even have to write a <code>handle</code> helper function. Haskell already understands monoids, so composition happens automatically. </p> <p> If you prefer, you could even skip the <code>handle</code> function too: </p> <p> <pre>*BusinessRules&gt; mconcat [slipForShipping, slipForRoyalty, activate, upgrade] $ Book "Blindsight" [Slip "Shipping" [Book "Blindsight"],Slip "Royalty" [Book "Blindsight"]]</pre> </p> <p> (Yes, you should also read <a href="http://amzn.to/1OSKj6Z">Blindsight</a>.) </p> <p> It's not that composition as such is built into Haskell, but rather that the language is designed around a powerful ability to model abstractions, and one of the built-in abstractions just happens to be monoids. You could argue, however, that many of Haskell's fundamental abstractions are built from category theory, and one of the fundamental characteristics of a category is how morphisms compose. </p> <h3 id="2b8ab9b2722940d093de8f7b4db7868d"> Summary <a href="#2b8ab9b2722940d093de8f7b4db7868d" title="permalink">#</a> </h3> <p> Composite are monoids. This article shows an example, starting with a solution in F#. You can translate the F# code to object-oriented C# and model the composition of business rules as a Composite. You can also translate the F# code 'the other way', to the strictly functional language Haskell, and thereby demonstrate that the solution is based on a monoid. </p> <p> <em>This article is a repost of <a href="https://blog.ndcconferences.com/composite-as-a-monoid-a-business-rules-example">a guest post on the NDC blog</a>, reproduced here with kind permission.</em> </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Project Arbitraries with view patterns http://blog.ploeh.dk/2018/05/14/project-arbitraries-with-view-patterns 2018-05-14T08:07:00+00:00 Mark Seemann <div id="post"> <p> <em>Write expressive property-based test with QuickCheck and view patterns.</em> </p> <p> Recently, I was writing some <a href="https://hackage.haskell.org/package/QuickCheck/docs/Test-QuickCheck.html">QuickCheck</a>-based tests of some business logic, and since the business logic in question involved a custom domain type called <code>Reservation</code>, I had to write an <code>Arbitrary</code> instance for it. Being a dutiful <a href="https://www.haskell.org">Haskell</a> programmer, I wrapped it in a <code>newtype</code> in order to prevent warnings about orphaned instances: </p> <p> <pre><span style="color:blue;">newtype</span>&nbsp;ArbReservation&nbsp;=&nbsp;ArbReservation&nbsp;{&nbsp;getReservation&nbsp;::&nbsp;Reservation&nbsp;}&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#2b91af;">Show</span>,&nbsp;<span style="color:#2b91af;">Eq</span>) <span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Arbitrary</span>&nbsp;<span style="color:blue;">ArbReservation</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;arbitrary&nbsp;=&nbsp;<span style="color:blue;">do</span> &nbsp;&nbsp;&nbsp;&nbsp;(d,&nbsp;e,&nbsp;n,&nbsp;Positive&nbsp;q,&nbsp;b)&nbsp;&lt;-&nbsp;arbitrary &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;$&nbsp;ArbReservation&nbsp;$&nbsp;Reservation&nbsp;d&nbsp;e&nbsp;n&nbsp;q&nbsp;b </pre> </p> <p> This is all fine as long as you just need one <code>Reservation</code> in a test, because in that case, you can simply pattern-match it out of <code>ArbReservation</code>: </p> <p> <pre>testProperty&nbsp;<span style="color:#a31515;">&quot;tryAccept&nbsp;reservation&nbsp;in&nbsp;the&nbsp;past&quot;</span>&nbsp;$&nbsp;\ &nbsp;&nbsp;(Positive&nbsp;capacity)&nbsp;(ArbReservation&nbsp;reservation) &nbsp;&nbsp;-&gt; &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;stub&nbsp;(IsReservationInFuture&nbsp;_&nbsp;next)&nbsp;=&nbsp;next&nbsp;False &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;stub&nbsp;(ReadReservations&nbsp;_&nbsp;next)&nbsp;=&nbsp;next&nbsp;<span style="color:blue;">[]</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;stub&nbsp;(Create&nbsp;_&nbsp;next)&nbsp;=&nbsp;next&nbsp;0 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;actual&nbsp;=&nbsp;iter&nbsp;stub&nbsp;$&nbsp;runMaybeT&nbsp;$&nbsp;tryAccept&nbsp;capacity&nbsp;reservation &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;<span style="color:blue;">in</span>&nbsp;&nbsp;isNothing&nbsp;actual </pre> </p> <p> Here, <code>reservation</code> is a <code>Reservation</code> value because it was pattern-matched out of <code>ArbReservation reservation</code>. That's just like <code>capacity</code> is an <code>Int</code>, because it was pattern-matched out of <code>Positive capacity</code>. </p> <p> Incidentally, in the spirit of <a href="http://blog.ploeh.dk/2018/05/07/inlined-hunit-test-lists">the previous article</a>, I'm here using in-lined properties implemented as lambda expressions. The lambda expressions use non-idiomatic formatting in order to make the tests more readable (and to prevent horizontal scrolling), but the gist of the matter is that the entire expression has the type <code>Positive Int -&gt; ArbReservation -&gt; Bool</code>. This is a <code>Testable</code> property because all the input types have <code>Arbitrary</code> instances. </p> <h3 id="e8b8ac40cade45db95315ebb8fa19ebc"> Discommodity creeps in <a href="#e8b8ac40cade45db95315ebb8fa19ebc" title="permalink">#</a> </h3> <p> That's fine for that test case, but for the next, I needed not only a single <code>Reservation</code> value, but also a list of <code>Reservation</code> values. Again, with QuickCheck, you can't write a property with a type like <code>Positive Int -&gt; [Reservation] -&gt; ArbReservation -&gt; Bool</code>, because there's no <code>Arbitrary</code> instance for <code>[Reservation]</code>. Instead, you'll need a property with the type <code>Positive Int -&gt; [ArbReservation] -&gt; ArbReservation -&gt; Bool</code>. </p> <p> One way to do that is to write the property like this: </p> <p> <pre>testProperty&nbsp;<span style="color:#a31515;">&quot;tryAccept&nbsp;reservation&nbsp;when&nbsp;capacity&nbsp;is&nbsp;insufficient&quot;</span>&nbsp;$&nbsp;\ &nbsp;&nbsp;(Positive&nbsp;i) &nbsp;&nbsp;reservations &nbsp;&nbsp;(ArbReservation&nbsp;reservation) &nbsp;&nbsp;-&gt; &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;stub&nbsp;(IsReservationInFuture&nbsp;_&nbsp;next)&nbsp;=&nbsp;next&nbsp;True &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;stub&nbsp;(ReadReservations&nbsp;_&nbsp;next)&nbsp;=&nbsp;next&nbsp;$&nbsp;getReservation&nbsp;&lt;$&gt;&nbsp;reservations &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;stub&nbsp;(Create&nbsp;_&nbsp;next)&nbsp;=&nbsp;next&nbsp;0 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;reservedSeats&nbsp;=&nbsp;<span style="color:blue;">sum</span>&nbsp;$&nbsp;reservationQuantity&nbsp;&lt;$&gt;&nbsp;getReservation&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;=&nbsp;iter&nbsp;stub&nbsp;$&nbsp;runMaybeT&nbsp;$&nbsp;tryAccept&nbsp;capacity&nbsp;reservation &nbsp;&nbsp;<span style="color:blue;">in</span>&nbsp;&nbsp;isNothing&nbsp;actual </pre> </p> <p> Here, <code>reservations</code> has type type <code>[ArbReservation]</code>, so every time the test needs to operate on the values, it first has to pull the <code>Reservation</code> values out of it using <code>getReservation &lt;$&gt; reservations</code>. That seems unnecessarily verbose and repetitive, so it'd be nice if a better option was available. </p> <h3 id="49c9bc081e7b41598fa7bb9052b747d0"> View pattern <a href="#49c9bc081e7b41598fa7bb9052b747d0" title="permalink">#</a> </h3> <p> Had I been writing <a href="http://fsharp.org">F#</a> code, I'd immediately be reaching for an <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/active-patterns">active pattern</a>, but this is Haskell. If there's one thing, though, I've learned about Haskell so far, it's that, if F# can do something, there's a very good chance Haskell can do it too - only, it may be called something else. </p> <p> With a vague sense that I'd seen something similar in some Haskell code somewhere, I went looking, and about fifteen minutes later I'd found what I was looking for: a little language extension called <em>view patterns</em>. Just add the language extension to the top of the file where you want to use it: </p> <p> <pre>{-#&nbsp;<span style="color:gray;">LANGUAGE</span>&nbsp;ViewPatterns&nbsp;#-}</pre> </p> <p> You can now change the property to pattern-match <code>reservations</code> out of a function call, so to speak: </p> <p> <pre>testProperty&nbsp;<span style="color:#a31515;">&quot;tryAccept&nbsp;reservation&nbsp;when&nbsp;capacity&nbsp;is&nbsp;insufficient&quot;</span>&nbsp;$&nbsp;\ &nbsp;&nbsp;(Positive&nbsp;i) &nbsp;&nbsp;(<span style="color:blue;">fmap</span>&nbsp;getReservation&nbsp;-&gt;&nbsp;reservations) &nbsp;&nbsp;(ArbReservation&nbsp;reservation) &nbsp;&nbsp;-&gt; &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;stub&nbsp;(IsReservationInFuture&nbsp;_&nbsp;next)&nbsp;=&nbsp;next&nbsp;True &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;stub&nbsp;(ReadReservations&nbsp;_&nbsp;next)&nbsp;=&nbsp;next&nbsp;reservations &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;stub&nbsp;(Create&nbsp;_&nbsp;next)&nbsp;=&nbsp;next&nbsp;0 &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;=&nbsp;iter&nbsp;stub&nbsp;$&nbsp;runMaybeT&nbsp;$&nbsp;tryAccept&nbsp;capacity&nbsp;reservation &nbsp;&nbsp;<span style="color:blue;">in</span>&nbsp;&nbsp;isNothing&nbsp;actual </pre> </p> <p> The function <code>getReservation</code> has the type <code>ArbReservation -&gt; Reservation</code>, so <code>fmap getReservation</code> is a partially applied function with the type <code>[ArbReservation] -&gt; [Reservation]</code>. In order to be able to call the overall lambda expression, the caller must supply an <code>[ArbReservation]</code> value to the view pattern, which means that the type of that argument must be <code>[ArbReservation]</code>. The view pattern then immediately unpacks the result of the function and gives you <code>reservations</code>, which is the return value of calling <code>fmap getReservation</code> with the input value(s). Thus, <code>reservations</code> has the type <code>[Reservation]</code>. </p> <p> The type of the entire property is now <code>Positive Int -&gt; [ArbReservation] -&gt; ArbReservation -&gt; Bool</code>. </p> <p> This removes some noise from the body of the property, so I find that this is a useful trick in this particular situation. </p> <h3 id="02cafa3f94eb4fe19e1ad19f7448d258"> Summary <a href="#02cafa3f94eb4fe19e1ad19f7448d258" title="permalink">#</a> </h3> <p> You can use the <em>view patterns</em> GHC language extension when you need to write a function that takes an argument of a particular type, but you never care about the original input, but instead immediately wish to project it to a different value. </p> <p> I haven't had much use for it before, but it seems to be useful in the context of QuickCheck properties. </p> </div> <div id="comments"> <hr> <h2 id="comments-header">Comments</h2> <div class="comment" id="81bcbcc0ff9142018fce53c744264ee2"> <div class="comment-author"><a href="https://benjamin.pizza/">Benjamin Hodgson</a></div> <div class="comment-content"> <p> I've seen folks wrap up the view pattern in a <a href="https://downloads.haskell.org/~ghc/8.4.2/docs/html/users_guide/glasgow_exts.html#pattern-synonyms">pattern synonym</a>: </p> <p> <pre><code> pattern ArbReservations :: [Reservation] -> [ArbReservation] pattern ArbReservations rs <- (coerce -> rs) where ArbReservations rs = coerce rs foo :: [ArbReservation] -> IO () foo (ArbReservations rs) = traverse print rs </code></pre> </p> <p> (<code>coerce</code> is usually more efficient than <code>fmap</code>.) </p> <p> OTOH I don't think orphan instances of <code>Arbitrary</code> are very harmful. It's unlikely that they'll get accidentally imported or overlap, because <code>Arbitrary</code> is purely used for testing. So in this specific case I'd probably just stick with an orphan instance and turn off the warning for that file. </p> </div> <div class="comment-date">2018-05-26 10:55 UTC</div> </div> <div class="comment" id="85761f5529fd4806a4e4202ed4b319c5"> <div class="comment-author"><a href="http://blog.ploeh.dk">Mark Seemann</a></div> <div class="comment-content"> <p> Benjamin, thank you for the <em>pattern synonyms</em> tip; I'll have to try that next time. </p> <p> Regarding orphaned instances, your point is something I've been considering myself, but I'm still at the point of my Haskell journey where I'm trying to understand the subtleties of the ecosystem, so I wasn't sure whether or not it'd be a good idea to allow orphaned <code>Arbitrary</code> instances. </p> <p> When you suggest turning off the warning for a file, do you mean adding an <code>{-# OPTIONS_GHC -fno-warn-orphans #-}</code> pragma, or did you have some other method in mind? </p> </div> <div class="comment-date">2018-05-27 7:54 UTC</div> </div> <div class="comment" id="dc078779dfd04a8a8411322269516ae0"> <div class="comment-author"><a href="https://benjamin.pizza/">Benjamin Hodgson</a></div> <div class="comment-content"> <p> Yep I meant <code>OPTIONS_GHC</code>. </p> <p> Orphan instances are problematic because of the possibility that they'll be imported unintentionally or overlap with another orphan instance. If you import two modules which both define orphan instances for the same type then there's no way for GHC to know which one you meant when you attempt to use them. Since instances aren't named you can't even specify it manually, and the compiler can't check for this scenario ahead of time because of separate compilation. (Non-orphans are guaranteed unique by the fact that you can't import the parent type/class without importing the instance.) </p> <p> In the case of <code>Arbitrary</code> these problems typically don't apply because the class is intended to be used for testing. <code>Arbitrary</code> instances are usually internal to your test project and not exported, so the potential for damage is small. </p> </div> <div class="comment-date">2018-05-27 14:08 UTC</div> </div> <div class="comment" id="295d2df911f1465eb14118085f47b3b1"> <div class="comment-author"><a href="http://blog.ploeh.dk">Mark Seemann</a></div> <div class="comment-content"> <p> Benjamin, thank you for elaborating. That all makes sense to me. </p> </div> <div class="comment-date">2018-05-27 16:06 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Inlined HUnit test lists http://blog.ploeh.dk/2018/05/07/inlined-hunit-test-lists 2018-05-07T12:41:00+00:00 Mark Seemann <div id="post"> <p> <em>An alternative way to organise tests lists with HUnit.</em> </p> <p> In the <a href="http://blog.ploeh.dk/2018/04/30/parametrised-unit-tests-in-haskell">previous article</a> you saw how to write <a href="http://xunitpatterns.com/Parameterized%20Test.html">parametrised test</a> with <a href="https://hackage.haskell.org/package/HUnit">HUnit</a>. While the tests themselves were elegant and readable (in my opinion), the composition of test lists left something to be desired. This article offers a different way to organise test lists. </p> <h3 id="d7a929c8507641759a43055ee6c4659f"> Duplication <a href="#d7a929c8507641759a43055ee6c4659f" title="permalink">#</a> </h3> <p> The main problem is one of duplication. Consider the <code>main</code> function for the test library, as defined in the previous article: </p> <p> <pre>main&nbsp;<span style="color:#666666;">=</span>&nbsp;defaultMain&nbsp;<span style="color:#666666;">$</span>&nbsp;hUnitTestToTests&nbsp;<span style="color:#666666;">$</span>&nbsp;<span style="color:#dd0000;">TestList</span>&nbsp;[ &nbsp;&nbsp;<span style="color:#a31515;">&quot;adjustToBusinessHours&nbsp;returns&nbsp;correct&nbsp;result&quot;</span>&nbsp;<span style="color:#666666;">~:</span>&nbsp;adjustToBusinessHoursReturnsCorrectResult, &nbsp;&nbsp;<span style="color:#a31515;">&quot;adjustToDutchBankDay&nbsp;returns&nbsp;correct&nbsp;result&quot;</span>&nbsp;<span style="color:#666666;">~:</span>&nbsp;adjustToDutchBankDayReturnsCorrectResult, &nbsp;&nbsp;<span style="color:#a31515;">&quot;Composed&nbsp;adjust&nbsp;returns&nbsp;correct&nbsp;result&quot;</span>&nbsp;<span style="color:#666666;">~:</span>&nbsp;composedAdjustReturnsCorrectResult&nbsp;]</pre> </p> <p> It annoys me that I have a function with a (somewhat) descriptive name, like <code>adjustToBusinessHoursReturnsCorrectResult</code>, but then I also have to give the test a label - in this case <code>"adjustToBusinessHours returns correct result"</code>. Not only is this duplication, but it also adds an extra maintenance overhead, because if I decide to rename the test, should I also rename the label? </p> <p> Why do you even need the label? When you run the test, that label is printed during the test run, so that you can see what happens: </p> <p> <pre>$ stack test --color never --ta "--plain" ZonedTimeAdjustment-0.1.0.0: test (suite: ZonedTimeAdjustment-test, args: --plain) :adjustToDutchBankDay returns correct result: : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] :adjustToBusinessHours returns correct result: : [OK] : [OK] : [OK] :Composed adjust returns correct result: : [OK] : [OK] : [OK] : [OK] : [OK] Test Cases Total Passed 20 20 Failed 0 0 Total 20 20</pre> </p> <p> I considered it redundant to give each test case in the parametrised tests their own labels, but I could have done that too, if I'd wanted to. </p> <p> What happens if you remove the labels? </p> <p> <pre>main&nbsp;<span style="color:#666666;">=</span>&nbsp;defaultMain&nbsp;<span style="color:#666666;">$</span>&nbsp;hUnitTestToTests&nbsp;<span style="color:#666666;">$</span>&nbsp;<span style="color:#dd0000;">TestList</span>&nbsp;<span style="color:#666666;">$</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;adjustToBusinessHoursReturnsCorrectResult &nbsp;&nbsp;<span style="color:#666666;">++</span>&nbsp;&nbsp;adjustToDutchBankDayReturnsCorrectResult &nbsp;&nbsp;<span style="color:#666666;">++</span>&nbsp;&nbsp;composedAdjustReturnsCorrectResult</pre> </p> <p> That compiles, but produces output like this: </p> <p> <pre>$ stack test --color never --ta "--plain" ZonedTimeAdjustment-0.1.0.0: test (suite: ZonedTimeAdjustment-test, args: --plain) : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] : [OK] Test Cases Total Passed 20 20 Failed 0 0 Total 20 20</pre> </p> <p> If you don't care about the labels, then that's a fine solution. On the other hand, if you <em>do</em> care about the labels, then a different approach is warranted. </p> <h3 id="9801f758146a43939d1347b64ab092f4"> Inlined test lists <a href="#9801f758146a43939d1347b64ab092f4" title="permalink">#</a> </h3> <p> Looking at an expression like <code>"Composed adjust returns correct result" ~: composedAdjustReturnsCorrectResult</code>, I find <code>"Composed adjust returns correct result"</code> more readable than <code>composedAdjustReturnsCorrectResult</code>, so if I want to reduce duplication, I want to go after a solution that names a test with a label, instead of a solution that names a test with a function name. </p> <p> What is <code>composedAdjustReturnsCorrectResult</code>? It's just the name of a <a href="https://en.wikipedia.org/wiki/Pure_function">pure function</a> (because its type is <code>[Test]</code>). Since it's <a href="https://en.wikipedia.org/wiki/Referential_transparency">referentially transparent</a>, it means that in the test list in <code>main</code>, I can replace the function with its body! I can do this with all three functions, although, in order to keep things simplified, I'm only going to show you two of them: </p> <p> <pre><span style="color:#600277;">main</span>&nbsp;::&nbsp;IO&nbsp;() main&nbsp;<span style="color:#666666;">=</span>&nbsp;defaultMain&nbsp;<span style="color:#666666;">$</span>&nbsp;hUnitTestToTests&nbsp;<span style="color:#666666;">$</span>&nbsp;<span style="color:#dd0000;">TestList</span>&nbsp;[ &nbsp;&nbsp;<span style="color:#a31515;">&quot;adjustToBusinessHours&nbsp;returns&nbsp;correct&nbsp;result&quot;</span>&nbsp;<span style="color:#666666;">~:</span>&nbsp;<span style="color:#af00db;">do</span> &nbsp;&nbsp;&nbsp;&nbsp;(dt,&nbsp;expected)&nbsp;<span style="color:#666666;">&lt;-</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">10</span>,&nbsp;<span style="color:#09885a;">2</span>)&nbsp;(<span style="color:#09885a;">6</span>,&nbsp;<span style="color:#09885a;">59</span>,&nbsp;&nbsp;<span style="color:#09885a;">4</span>)&nbsp;<span style="color:#09885a;">0</span>,&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">10</span>,&nbsp;<span style="color:#09885a;">2</span>)&nbsp;(<span style="color:#09885a;">9</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>)&nbsp;<span style="color:#09885a;">0</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">10</span>,&nbsp;<span style="color:#09885a;">2</span>)&nbsp;(<span style="color:#09885a;">9</span>,&nbsp;<span style="color:#09885a;">42</span>,&nbsp;<span style="color:#09885a;">41</span>)&nbsp;<span style="color:#09885a;">0</span>,&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">10</span>,&nbsp;<span style="color:#09885a;">2</span>)&nbsp;(<span style="color:#09885a;">9</span>,&nbsp;<span style="color:#09885a;">42</span>,&nbsp;<span style="color:#09885a;">41</span>)&nbsp;<span style="color:#09885a;">0</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">10</span>,&nbsp;<span style="color:#09885a;">2</span>)&nbsp;(<span style="color:#09885a;">19</span>,&nbsp;<span style="color:#09885a;">1</span>,&nbsp;<span style="color:#09885a;">32</span>)&nbsp;<span style="color:#09885a;">0</span>,&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">10</span>,&nbsp;<span style="color:#09885a;">3</span>)&nbsp;(<span style="color:#09885a;">9</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>)&nbsp;<span style="color:#09885a;">0</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;] &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;actual&nbsp;<span style="color:#666666;">=</span>&nbsp;adjustToBusinessHours&nbsp;dt &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;<span style="color:#666666;">$</span>&nbsp;<span style="color:#dd0000;">ZT</span>&nbsp;expected&nbsp;<span style="color:#666666;">~=?</span>&nbsp;<span style="color:#dd0000;">ZT</span>&nbsp;actual &nbsp;&nbsp;, &nbsp;&nbsp;<span style="color:#a31515;">&quot;Composed&nbsp;adjust&nbsp;returns&nbsp;correct&nbsp;result&quot;</span>&nbsp;<span style="color:#666666;">~:</span>&nbsp;<span style="color:#af00db;">do</span> &nbsp;&nbsp;&nbsp;&nbsp;(dt,&nbsp;expected)&nbsp;<span style="color:#666666;">&lt;-</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">1</span>,&nbsp;<span style="color:#09885a;">31</span>)&nbsp;(&nbsp;<span style="color:#09885a;">7</span>,&nbsp;<span style="color:#09885a;">45</span>,&nbsp;<span style="color:#09885a;">55</span>)&nbsp;&nbsp;&nbsp;<span style="color:#09885a;">2</span>&nbsp;,&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">2</span>,&nbsp;<span style="color:#09885a;">28</span>)&nbsp;(&nbsp;<span style="color:#09885a;">7</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>)&nbsp;<span style="color:#09885a;">0</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">2</span>,&nbsp;&nbsp;<span style="color:#09885a;">6</span>)&nbsp;(<span style="color:#09885a;">10</span>,&nbsp;&nbsp;<span style="color:#09885a;">3</span>,&nbsp;&nbsp;<span style="color:#09885a;">2</span>)&nbsp;&nbsp;&nbsp;<span style="color:#09885a;">1</span>&nbsp;,&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">3</span>,&nbsp;&nbsp;<span style="color:#09885a;">6</span>)&nbsp;(&nbsp;<span style="color:#09885a;">9</span>,&nbsp;&nbsp;<span style="color:#09885a;">3</span>,&nbsp;&nbsp;<span style="color:#09885a;">2</span>)&nbsp;<span style="color:#09885a;">0</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">2</span>,&nbsp;&nbsp;<span style="color:#09885a;">9</span>)&nbsp;(&nbsp;<span style="color:#09885a;">4</span>,&nbsp;<span style="color:#09885a;">20</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>)&nbsp;&nbsp;&nbsp;<span style="color:#09885a;">0</span>&nbsp;,&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">3</span>,&nbsp;&nbsp;<span style="color:#09885a;">9</span>)&nbsp;(&nbsp;<span style="color:#09885a;">9</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>)&nbsp;<span style="color:#09885a;">0</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">2</span>,&nbsp;<span style="color:#09885a;">12</span>)&nbsp;(<span style="color:#09885a;">16</span>,&nbsp;&nbsp;<span style="color:#09885a;">2</span>,&nbsp;<span style="color:#09885a;">11</span>)&nbsp;&nbsp;&nbsp;<span style="color:#09885a;">0</span>&nbsp;,&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">3</span>,&nbsp;<span style="color:#09885a;">10</span>)&nbsp;(<span style="color:#09885a;">16</span>,&nbsp;&nbsp;<span style="color:#09885a;">2</span>,&nbsp;<span style="color:#09885a;">11</span>)&nbsp;<span style="color:#09885a;">0</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">3</span>,&nbsp;<span style="color:#09885a;">14</span>)&nbsp;(<span style="color:#09885a;">13</span>,&nbsp;<span style="color:#09885a;">48</span>,&nbsp;<span style="color:#09885a;">29</span>)&nbsp;(<span style="color:#666666;">-</span><span style="color:#09885a;">1</span>),&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">4</span>,&nbsp;<span style="color:#09885a;">13</span>)&nbsp;(<span style="color:#09885a;">14</span>,&nbsp;<span style="color:#09885a;">48</span>,&nbsp;<span style="color:#09885a;">29</span>)&nbsp;<span style="color:#09885a;">0</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;] &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;adjustments&nbsp;<span style="color:#666666;">=</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;reverse&nbsp;[adjustToNextMonth,&nbsp;adjustToBusinessHours,&nbsp;adjustToDutchBankDay,&nbsp;adjustToUtc] &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;adjust&nbsp;<span style="color:#666666;">=</span>&nbsp;appEndo&nbsp;<span style="color:#666666;">$</span>&nbsp;mconcat&nbsp;<span style="color:#666666;">$</span>&nbsp;<span style="color:#dd0000;">Endo</span>&nbsp;<span style="color:#666666;">&lt;$&gt;</span>&nbsp;adjustments &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;actual&nbsp;<span style="color:#666666;">=</span>&nbsp;adjust&nbsp;dt &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;<span style="color:#666666;">$</span>&nbsp;<span style="color:#dd0000;">ZT</span>&nbsp;expected&nbsp;<span style="color:#666666;">~=?</span>&nbsp;<span style="color:#dd0000;">ZT</span>&nbsp;actual &nbsp;&nbsp;]</pre> </p> <p> In order to keep the code listing to a reasonable length, I didn't include the third test <code>"adjustToDutchBankDay returns correct result"</code>, but it works in exactly the same way. </p> <p> This is a list with two values. You can see that the values are separated by a <code>,</code>, just like list elements normally are. What's unusual, however, is that each element in the list is defined with a multi-line <code>do</code> block. </p> <p> In C# and F#, I'm used to being able to just write new test functions, and they're automatically picked up by convention and executed by the test runner. I wouldn't be at all surprised if there was a mechanism using Template Haskell that enables something similar, but I find that there's something appealing about treating tests as first-class values all the way. </p> <p> By inlining the tests, I can retain my F# and C# workflow. Just add a new test within the list, and it's automatically picked up by the <code>main</code> function. Not only that, but it's no longer possible to write a test that compiles, but is never executed by the test runner because it has the wrong type. This occasionally happens to me in F#, but with the technique outlined here, if I accidentally give the test the wrong type, it's not going to compile. </p> <h3 id="c9303b8865dc42b0a60bac2b9471fc13"> Conclusion <a href="#c9303b8865dc42b0a60bac2b9471fc13" title="permalink">#</a> </h3> <p> Since HUnit tests are first-class values, you can define them inlined in test lists. For larger code bases, I'd assume that you'd want to spread your unit tests across multiple modules. In that case, I suppose that you could have each test module export a <code>[Test]</code> value. In the test library's <code>main</code> function, you'd need to manually concatenate all the exported test lists together, so a small maintenance burden remains. When you add a new test module, you'd have to add its exported tests to <code>main</code>. </p> <p> I wouldn't be surprised, however, if a clever reader could point out to me how to avoid that as well. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Parametrised unit tests in Haskell http://blog.ploeh.dk/2018/04/30/parametrised-unit-tests-in-haskell 2018-04-30T07:04:00+00:00 Mark Seemann <div id="post"> <p> <em>Here's a way to write parametrised unit tests in Haskell.</em> </p> <p> Sometimes you'd like to execute the same (unit) test for a number of test cases. The only thing that varies is the input values, and the expected outcome. The actual test code is the same for all test cases. Among object-oriented programmers, this is known as a <a href="http://xunitpatterns.com/Parameterized%20Test.html">parametrised test</a>. </p> <p> When I recently searched the web for how to do parametrised tests in <a href="https://www.haskell.org">Haskell</a>, I could only find articles that talked about property-based testing, mostly with <a href="https://hackage.haskell.org/package/QuickCheck">QuickCheck</a>. I normally prefer property-based testing, but sometimes, I'd rather like to run a test with some deterministic test cases that are visible and readable in the code itself. </p> <p> Here's one way I found that I could do that in Haskell. </p> <h3 id="1717430a5a3048629121ab7831c1339d"> Testing date and time adjustments in C# <a href="#1717430a5a3048629121ab7831c1339d" title="permalink">#</a> </h3> <p> In <a href="http://blog.ploeh.dk/2017/11/13/endomorphism-monoid">an earlier article</a>, I discussed how to model date and time adjustments as a <a href="http://blog.ploeh.dk/2017/10/06/monoids">monoid</a>. The example code was written in C#, and I used a few tests to demonstrate that the composition of adjustments work as intended: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-01-31T07:45:55+2&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;2017-02-28T07:00:00Z&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-02-06T10:03:02+1&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;2017-03-06T09:03:02Z&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-02-09T04:20:00Z&quot;</span>&nbsp;,&nbsp;<span style="color:#a31515;">&quot;2017-03-09T09:00:00Z&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-02-12T16:02:11Z&quot;</span>&nbsp;,&nbsp;<span style="color:#a31515;">&quot;2017-03-10T16:02:11Z&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-03-14T13:48:29-1&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;2017-04-13T14:48:29Z&quot;</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;AccumulatedAdjustReturnsCorrectResult( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;dtS, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;expectedS) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;dt&nbsp;=&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>.Parse(dtS); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;sut&nbsp;=&nbsp;<span style="color:#2b91af;">DateTimeOffsetAdjustment</span>.Accumulate( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">NextMonthAdjustment</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">BusinessHoursAdjustment</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">DutchBankDayAdjustment</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">UtcAdjustment</span>()); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;sut.Adjust(dt); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#2b91af;">DateTimeOffset</span>.Parse(expectedS),&nbsp;actual); }</pre> </p> <p> The above parametrised test uses <a href="https://xunit.github.io">xUnit.net</a> (particularly its <code>Theory</code> feature) to execute the same test code for five test cases. Here's another example: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-10-02T06:59:04Z&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;2017-10-02T09:00:00Z&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-10-02T09:42:41Z&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;2017-10-02T09:42:41Z&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-10-02T19:01:32Z&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;2017-10-03T09:00:00Z&quot;</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;AdjustReturnsCorrectResult(<span style="color:blue;">string</span>&nbsp;dts,&nbsp;<span style="color:blue;">string</span>&nbsp;expectedS) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;dt&nbsp;=&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>.Parse(dts); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;sut&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">BusinessHoursAdjustment</span>(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;sut.Adjust(dt); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#2b91af;">DateTimeOffset</span>.Parse(expectedS),&nbsp;actual); }</pre> </p> <p> This one covers the three code paths through <code>BusinessHoursAdjustment.Adjust</code>. </p> <p> These tests are similar, so they share some good and bad qualities. </p> <p> On the positive side, I like how <em>readable</em> such tests are. The test code is only a few lines of code, and the test cases (input, and expected output) are in close proximity to the code. Unless you're on a phone with a small screen, you can easily see all of it at once. </p> <p> For a problem like this, I felt that I preferred examples rather than using property-based testing. If the date and time is this, then the adjusted result should be that, and so on. When we <em>read</em> code, we tend to prefer examples. Good documentation often contains examples, and for those of us who consider tests documentation, including examples in tests should advance that cause. </p> <p> On the negative side, tests like these still contain noise. Most of it relates to the problem that xUnit.net tests aren't first-class values. These tests actually ought to take a <code>DateTimeOffset</code> value as input, and compare it to another, expected <code>DateTimeOffset</code> value. Unfortunately, <code>DateTimeOffset</code> values aren't constants, so you can't use them in attributes, like the <code>[InlineData]</code> attribute. </p> <p> There are other workarounds than the one I ultimately chose, but none that are as simple (that I'm aware of). Strings are constants, so you can put formatted date and time strings in the <code>[InlineData]</code> attributes, but the cost of doing this is two calls to <code>DateTimeOffset.Parse</code>. Perhaps this isn't a big price, you think, but it does make me wish for something prettier. </p> <h3 id="df8f3de4ba284893b551b470a6e7c579"> Comparing date and time <a href="#df8f3de4ba284893b551b470a6e7c579" title="permalink">#</a> </h3> <p> In order to port the above tests to Haskell, I used <a href="http://haskellstack.org">Stack</a> to create a new project with <a href="https://hackage.haskell.org/package/HUnit">HUnit</a> as the unit testing library. </p> <p> The Haskell equivalent to <code>DateTimeOffset</code> is called <code>ZonedTime</code>. One problem with <code>ZonedTime</code> values is that you can't readily compare them; the type isn't an <code>Eq</code> instance. There are good reasons for that, but for the purposes of unit testing, I wanted to be able to compare them, so I defined this helper data type: </p> <p> <pre><span style="color:blue;">newtype</span>&nbsp;<span style="color:#dd0000;">ZonedTimeEq</span>&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">ZT</span>&nbsp;<span style="color:#dd0000;">ZonedTime</span>&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#a31515;">Show</span>) <span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Eq</span>&nbsp;<span style="color:blue;">ZonedTimeEq</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;<span style="color:#dd0000;">ZT</span>&nbsp;(<span style="color:#dd0000;">ZonedTime</span>&nbsp;lt1&nbsp;tz1)&nbsp;<span style="color:#666666;">==</span>&nbsp;<span style="color:#dd0000;">ZT</span>&nbsp;(<span style="color:#dd0000;">ZonedTime</span>&nbsp;lt2&nbsp;tz2)&nbsp;<span style="color:#666666;">=</span>&nbsp;lt1&nbsp;<span style="color:#666666;">==</span>&nbsp;lt2&nbsp;<span style="color:#666666;">&amp;&amp;</span>&nbsp;tz1&nbsp;<span style="color:#666666;">==</span>&nbsp;tz2</pre> </p> <p> This enables me to compare two <code>ZonedTimeEq</code> values, which are only considered equal if they represent the same date, the same time, and the same time zone. </p> <h3 id="57e07c4d36a644889271d392581ae0f3"> Test Utility <a href="#57e07c4d36a644889271d392581ae0f3" title="permalink">#</a> </h3> <p> I also added a little function for creating <code>ZonedTime</code> values: </p> <p> <pre>zt&nbsp;(y,&nbsp;mth,&nbsp;d)&nbsp;(h,&nbsp;m,&nbsp;s)&nbsp;tz&nbsp;<span style="color:#666666;">=</span> &nbsp;&nbsp;<span style="color:#dd0000;">ZonedTime</span>&nbsp;(<span style="color:#dd0000;">LocalTime</span>&nbsp;(fromGregorian&nbsp;y&nbsp;mth&nbsp;d)&nbsp;(<span style="color:#dd0000;">TimeOfDay</span>&nbsp;h&nbsp;m&nbsp;s))&nbsp;(hoursToTimeZone&nbsp;tz)</pre> </p> <p> The motivation is simply that, as you can tell, creating a <code>ZonedTime</code> value requires a verbose expression. Clearly, the <code>ZonedTime</code> API is flexible, but in order to define some test cases, I found it advantageous to trade readability for flexibility. The <code>zt</code> function enables me to compactly define some <code>ZonedTime</code> values for my test cases. </p> <h3 id="941af2b4f00f4fa7b0683f1590879e61"> Testing business hours in Haskell <a href="#941af2b4f00f4fa7b0683f1590879e61" title="permalink">#</a> </h3> <p> In HUnit, a test is either a <code>Test</code>, a list of <code>Test</code> values, or an impure assertion. For a parametrised test, a <code>[Test]</code> sounded promising. At the beginning, I struggled with finding a readable way to express the tests. I wanted to be able to start with a list of test cases (inputs and expected outputs), and then <code>fmap</code> them to an executable test. At first, the readability goal seemed elusive, until I realised that I can also use <code>do</code> notation with lists (since they're monads): </p> <p> <pre><span style="color:#600277;">adjustToBusinessHoursReturnsCorrectResult</span>&nbsp;::&nbsp;[<span style="color:blue;">Test</span>] adjustToBusinessHoursReturnsCorrectResult&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#af00db;">do</span> &nbsp;&nbsp;(dt,&nbsp;expected)&nbsp;<span style="color:#666666;">&lt;-</span> &nbsp;&nbsp;&nbsp;&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">10</span>,&nbsp;<span style="color:#09885a;">2</span>)&nbsp;(<span style="color:#09885a;">6</span>,&nbsp;<span style="color:#09885a;">59</span>,&nbsp;&nbsp;<span style="color:#09885a;">4</span>)&nbsp;<span style="color:#09885a;">0</span>,&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">10</span>,&nbsp;<span style="color:#09885a;">2</span>)&nbsp;(<span style="color:#09885a;">9</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>)&nbsp;<span style="color:#09885a;">0</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">10</span>,&nbsp;<span style="color:#09885a;">2</span>)&nbsp;(<span style="color:#09885a;">9</span>,&nbsp;<span style="color:#09885a;">42</span>,&nbsp;<span style="color:#09885a;">41</span>)&nbsp;<span style="color:#09885a;">0</span>,&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">10</span>,&nbsp;<span style="color:#09885a;">2</span>)&nbsp;(<span style="color:#09885a;">9</span>,&nbsp;<span style="color:#09885a;">42</span>,&nbsp;<span style="color:#09885a;">41</span>)&nbsp;<span style="color:#09885a;">0</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">10</span>,&nbsp;<span style="color:#09885a;">2</span>)&nbsp;(<span style="color:#09885a;">19</span>,&nbsp;<span style="color:#09885a;">1</span>,&nbsp;<span style="color:#09885a;">32</span>)&nbsp;<span style="color:#09885a;">0</span>,&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">10</span>,&nbsp;<span style="color:#09885a;">3</span>)&nbsp;(<span style="color:#09885a;">9</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>)&nbsp;<span style="color:#09885a;">0</span>) &nbsp;&nbsp;&nbsp;&nbsp;] &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;actual&nbsp;<span style="color:#666666;">=</span>&nbsp;adjustToBusinessHours&nbsp;dt &nbsp;&nbsp;return&nbsp;<span style="color:#666666;">$</span>&nbsp;<span style="color:#dd0000;">ZT</span>&nbsp;expected&nbsp;<span style="color:#666666;">~=?</span>&nbsp;<span style="color:#dd0000;">ZT</span>&nbsp;actual</pre> </p> <p> This is the same test as the above C# test named <code>AdjustReturnsCorrectResult</code>, and it's about the same size as well. Since the test is written using <code>do</code> notation, you can take a list of test cases and operate on each test case at a time. Although the test creates a list of tuples, the <code>&lt;-</code> arrow pulls each <code>(ZonedTime, ZonedTime)</code> tuple out of the list and binds it to <code>(dt, expected)</code>. </p> <p> This test literally consists of only three expressions, so according to my normal <a href="http://blog.ploeh.dk/2013/06/24/a-heuristic-for-formatting-code-according-to-the-aaa-pattern">heuristic for test formatting</a>, I don't even need white space to indicate the three phases of the <a href="http://wiki.c2.com/?ArrangeActAssert">AAA pattern</a>. The first expression sets up the test case <code>(dt, expected)</code>. </p> <p> The next expression exercises the System Under Test - in this case the <code>adjustToBusinessHours</code> function. That's simply a function call. </p> <p> The third expression verifies the result. It uses HUnit's <code>~=?</code> operator to compare the expected and the actual values. Since <code>ZonedTime</code> isn't an <code>Eq</code> instance, both values are converted to <code>ZonedTimeEq</code> values. The <code>~=?</code> operator returns a <code>Test</code> value, and since the entire test takes place inside a <code>do</code> block, you must <code>return</code> it. Since this particular <code>do</code> block takes place inside the list monad, the type of <code>adjustToBusinessHoursReturnsCorrectResult</code> is <code>[Test]</code>. I added the type annotation for the benefit of you, dear reader, but technically, it's not required. </p> <h3 id="45bb86711997438386258c9ddc5d94dc"> Testing the composed function <a href="#45bb86711997438386258c9ddc5d94dc" title="permalink">#</a> </h3> <p> Translating the <code>AccumulatedAdjustReturnsCorrectResult</code> C# test to Haskell follows the same recipe: </p> <p> <pre><span style="color:#600277;">composedAdjustReturnsCorrectResult</span>&nbsp;::&nbsp;[<span style="color:blue;">Test</span>] composedAdjustReturnsCorrectResult&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#af00db;">do</span> &nbsp;&nbsp;(dt,&nbsp;expected)&nbsp;<span style="color:#666666;">&lt;-</span> &nbsp;&nbsp;&nbsp;&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">1</span>,&nbsp;<span style="color:#09885a;">31</span>)&nbsp;(&nbsp;<span style="color:#09885a;">7</span>,&nbsp;<span style="color:#09885a;">45</span>,&nbsp;<span style="color:#09885a;">55</span>)&nbsp;&nbsp;&nbsp;<span style="color:#09885a;">2</span>&nbsp;,&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">2</span>,&nbsp;<span style="color:#09885a;">28</span>)&nbsp;(&nbsp;<span style="color:#09885a;">7</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>)&nbsp;<span style="color:#09885a;">0</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">2</span>,&nbsp;&nbsp;<span style="color:#09885a;">6</span>)&nbsp;(<span style="color:#09885a;">10</span>,&nbsp;&nbsp;<span style="color:#09885a;">3</span>,&nbsp;&nbsp;<span style="color:#09885a;">2</span>)&nbsp;&nbsp;&nbsp;<span style="color:#09885a;">1</span>&nbsp;,&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">3</span>,&nbsp;&nbsp;<span style="color:#09885a;">6</span>)&nbsp;(&nbsp;<span style="color:#09885a;">9</span>,&nbsp;&nbsp;<span style="color:#09885a;">3</span>,&nbsp;&nbsp;<span style="color:#09885a;">2</span>)&nbsp;<span style="color:#09885a;">0</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">2</span>,&nbsp;&nbsp;<span style="color:#09885a;">9</span>)&nbsp;(&nbsp;<span style="color:#09885a;">4</span>,&nbsp;<span style="color:#09885a;">20</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>)&nbsp;&nbsp;&nbsp;<span style="color:#09885a;">0</span>&nbsp;,&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">3</span>,&nbsp;&nbsp;<span style="color:#09885a;">9</span>)&nbsp;(&nbsp;<span style="color:#09885a;">9</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>,&nbsp;&nbsp;<span style="color:#09885a;">0</span>)&nbsp;<span style="color:#09885a;">0</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">2</span>,&nbsp;<span style="color:#09885a;">12</span>)&nbsp;(<span style="color:#09885a;">16</span>,&nbsp;&nbsp;<span style="color:#09885a;">2</span>,&nbsp;<span style="color:#09885a;">11</span>)&nbsp;&nbsp;&nbsp;<span style="color:#09885a;">0</span>&nbsp;,&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">3</span>,&nbsp;<span style="color:#09885a;">10</span>)&nbsp;(<span style="color:#09885a;">16</span>,&nbsp;&nbsp;<span style="color:#09885a;">2</span>,&nbsp;<span style="color:#09885a;">11</span>)&nbsp;<span style="color:#09885a;">0</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">3</span>,&nbsp;<span style="color:#09885a;">14</span>)&nbsp;(<span style="color:#09885a;">13</span>,&nbsp;<span style="color:#09885a;">48</span>,&nbsp;<span style="color:#09885a;">29</span>)&nbsp;(<span style="color:#666666;">-</span><span style="color:#09885a;">1</span>),&nbsp;zt&nbsp;(<span style="color:#09885a;">2017</span>,&nbsp;<span style="color:#09885a;">4</span>,&nbsp;<span style="color:#09885a;">13</span>)&nbsp;(<span style="color:#09885a;">14</span>,&nbsp;<span style="color:#09885a;">48</span>,&nbsp;<span style="color:#09885a;">29</span>)&nbsp;<span style="color:#09885a;">0</span>) &nbsp;&nbsp;&nbsp;&nbsp;] &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;adjustments&nbsp;<span style="color:#666666;">=</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;reverse&nbsp;[adjustToNextMonth,&nbsp;adjustToBusinessHours,&nbsp;adjustToDutchBankDay,&nbsp;adjustToUtc] &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;adjust&nbsp;<span style="color:#666666;">=</span>&nbsp;appEndo&nbsp;<span style="color:#666666;">$</span>&nbsp;mconcat&nbsp;<span style="color:#666666;">$</span>&nbsp;<span style="color:#dd0000;">Endo</span>&nbsp;<span style="color:#666666;">&lt;$&gt;</span>&nbsp;adjustments &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;actual&nbsp;<span style="color:#666666;">=</span>&nbsp;adjust&nbsp;dt &nbsp;&nbsp;return&nbsp;<span style="color:#666666;">$</span>&nbsp;<span style="color:#dd0000;">ZT</span>&nbsp;expected&nbsp;<span style="color:#666666;">~=?</span>&nbsp;<span style="color:#dd0000;">ZT</span>&nbsp;actual</pre> </p> <p> The only notable difference is that this unit test consists of five expressions, so according to my formatting heuristic, I inserted some blank lines in order to make it easier to distinguish the three AAA phases from each other. </p> <h3 id="fb38a830884b4a1ba15b29e0b5dffbfb"> Running tests <a href="#fb38a830884b4a1ba15b29e0b5dffbfb" title="permalink">#</a> </h3> <p> I also wrote a third test called <code>adjustToDutchBankDayReturnsCorrectResult</code>, but that one is so similar to the two you've already seen that I see no point showing it here. In order to run all three tests, I define the tests' <code>main</code> function as such: </p> <p> <pre>main&nbsp;<span style="color:#666666;">=</span>&nbsp;defaultMain&nbsp;<span style="color:#666666;">$</span>&nbsp;hUnitTestToTests&nbsp;<span style="color:#666666;">$</span>&nbsp;<span style="color:#dd0000;">TestList</span>&nbsp;[ &nbsp;&nbsp;<span style="color:#a31515;">&quot;adjustToBusinessHours&nbsp;returns&nbsp;correct&nbsp;result&quot;</span>&nbsp;<span style="color:#666666;">~:</span>&nbsp;adjustToBusinessHoursReturnsCorrectResult, &nbsp;&nbsp;<span style="color:#a31515;">&quot;adjustToDutchBankDay&nbsp;returns&nbsp;correct&nbsp;result&quot;</span>&nbsp;<span style="color:#666666;">~:</span>&nbsp;adjustToDutchBankDayReturnsCorrectResult, &nbsp;&nbsp;<span style="color:#a31515;">&quot;Composed&nbsp;adjust&nbsp;returns&nbsp;correct&nbsp;result&quot;</span>&nbsp;<span style="color:#666666;">~:</span>&nbsp;composedAdjustReturnsCorrectResult&nbsp;]</pre> </p> <p> This uses <code>defaultMain</code> from <a href="https://hackage.haskell.org/package/test-framework">test-framework</a>, and <code>hUnitTestToTests</code> from <a href="https://hackage.haskell.org/package/test-framework-hunit">test-framework-hunit</a>. </p> <p> I'm not happy about the duplication of text and test names, and the maintenance burden implied by having to explicitly add every test function to the test list. It's too easy to forget to add a test after you've written it. In the next article, I'll demonstrate an alternative way to compose the tests so that duplication is reduced. </p> <h3 id="fd998b62c43942c7901f496b1e4205e0"> Conclusion <a href="#fd998b62c43942c7901f496b1e4205e0" title="permalink">#</a> </h3> <p> Since HUnit tests are first-class values, you can manipulate and compose them just like any other value. That includes passing them around in lists and binding them with <code>do</code> notation. Once you figure out how to write parametrised tests with HUnit, it's easy, readable, and elegant. </p> <p> The overall configuration of the test runner, however, leaves a bit to be desired, so that's the topic for the next article. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/05/07/inlined-hunit-test-lists">Inlined HUnit test lists</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Null Object as identity http://blog.ploeh.dk/2018/04/23/null-object-as-identity 2018-04-23T07:55:00+00:00 Mark Seemann <div id="post"> <p> <em>When can you implement a Null Object? When the return types of your methods are monoids.</em> </p> <p> This article is part of <a href="http://blog.ploeh.dk/2018/03/05/some-design-patterns-as-universal-abstractions">a series of articles about design patterns and their category theory counterparts</a>. In a <a href="http://blog.ploeh.dk/2018/03/12/composite-as-a-monoid">previous article</a> you learned how there's a strong relationship between the <a href="https://en.wikipedia.org/wiki/Composite_pattern">Composite</a> design pattern and <a href="http://blog.ploeh.dk/2017/10/06/monoids">monoids</a>. In this article you'll see that the <a href="https://en.wikipedia.org/wiki/Null_Object_pattern">Null Object</a> pattern is essentially a special case of the Composite pattern. </p> <p> I also think that there's a relationship between monoidal <em>identity</em> and the Null Object pattern similar to the relationship between Composite and monoids in general: </p> <p> <img src="/content/binary/null-object-identity-set-diagram.png" alt="Set diagram showing identity as a subset of Null Object."> </p> <p> Once more, I don't claim that an isomorphism exists. You may be able to produce Null Object examples that aren't monoidal, but on the other hand, I believe that all identities are Null Objects. </p> <h3 id="b082690114af4768ac6171438c7c7657"> Null Object <a href="#b082690114af4768ac6171438c7c7657" title="permalink">#</a> </h3> <p> While the Null Object design pattern isn't one of the patterns covered in <a href="http://amzn.to/XBYukB">Design Patterns</a>, I consider it a <em>structural pattern</em> because Composite is a structural pattern, and Null Object is a special case of Composite. </p> <p> Bobby Woolf's <a href="http://amzn.to/1dEKjcj">original text</a> contains an example in <a href="https://en.wikipedia.org/wiki/Smalltalk">Smalltalk</a>, and while I'm no Smalltalk expert, I think a fair translation to C# would be an interface like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IController</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">bool</span>&nbsp;IsControlWanted(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">bool</span>&nbsp;IsControlActive(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">void</span>&nbsp;Startup(); }</pre> </p> <p> The idea behind the Null Object pattern is to add an implementation that 'does nothing', which in the example would be this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">NullController</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IController</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;IsControlActive() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;IsControlWanted() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;Startup() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Woolf calls his implementation <code>NoController</code>, but I find it more intent-revealing to call it <code>NullController</code>. Both of the Boolean methods return <code>false</code>, and the <code>Startup</code> method literally does nothing. </p> <h3 id="862afa3095a847ba82c234ee1371dd70"> Doing nothing <a href="#862afa3095a847ba82c234ee1371dd70" title="permalink">#</a> </h3> <p> What exactly does it mean to 'do nothing'? In the case of the <code>Startup</code> method, it's clear, because it's a bona fide <a href="https://en.wikipedia.org/wiki/NOP">no-op</a>. This is possible for all methods without return values (i.e. methods that return <code>void</code>), but for all other methods, the compiler will insist on a return value. </p> <p> For <code>IsControlActive</code> and <code>IsControlWanted</code>, Woolf solves this by returning <code>false</code>. </p> <p> Is <code>false</code> always the correct 'do nothing' value for Booleans? And what should you return if a method returns an integer, a string, or a custom type? The original text is vague on that question: <blockquote> "Exactly what "do nothing" means is subjective and depends on the sort of behavior the Client is expecting." </blockquote> Sometimes, you can't get any closer than that, but I think that often it's possible to be more specific. </p> <h3 id="786916d104f949ce913ab94e6a0fafdc"> Doing nothing as identity <a href="#786916d104f949ce913ab94e6a0fafdc" title="permalink">#</a> </h3> <p> From <a href="http://blog.ploeh.dk/2018/01/15/unit-isomorphisms">unit isomorphisms</a> you know that methods without return values are isomorphic to methods that return <em>unit</em>. You also know that <em>unit</em> is a monoid. What does <em>unit</em> and <code>bool</code> have in common? They both form monoids; <code>bool</code>, in fact, forms four different monoids, of which <em>all</em> and <em>any</em> are the best-known. </p> <p> In my experience, you can implement the Null Object pattern by returning various 'do nothing' values, depending on their types: <ul> <li>For <code>bool</code>, return a constant value. Usually, <code>false</code> is the appropriate 'do nothing' value, but it does depend on the semantics of the operation.</li> <li>For <code>string</code>, return <code>""</code>.</li> <li>For collections, return an empty collection.</li> <li>For numbers, return a constant value, such as <code>0</code>.</li> <li>For <code>void</code>, do nothing, which is equivalent to returning <em>unit</em>.</li> </ul> What all of these have in common is that they return the <em>identity</em> of the monoid in question. Keep in mind that for some types, such as <code>bool</code> and <code>int</code>, more than one monoid exist, and the identity depends on which one you pick: <ul> <li>The identity for the <em>any</em> monoid is <code>false</code>.</li> <li>The <a href="http://blog.ploeh.dk/2017/10/10/strings-lists-and-sequences-as-a-monoid">identity for <code>string</code> is <code>""</code></a>.</li> <li>The identity for collections is the empty collection.</li> <li>The identity for the <em>addition</em> monoid is <code>0</code>.</li> <li>The identity for <em>unit</em> is <em>unit</em>.</li> </ul> Recall what the <em>identity</em> of a monoid is: it's the value that, when applied to another value, doesn't change the other value: </p> <p> <pre>foo.Op(<span style="color:#2b91af;">Foo</span>.Identity)&nbsp;==&nbsp;foo</pre> </p> <p> In other words: the <em>identity does nothing!</em> </p> <p> As a preliminary result, then, when all return values of your interface form monoids, you can create a Null Object. </p> <h3 id="ec81b9f4281e4c4c909d1dc606056967"> Relationship with Composite <a href="#ec81b9f4281e4c4c909d1dc606056967" title="permalink">#</a> </h3> <p> In the previous article, you saw how the Composite design pattern was equivalent with the <a href="https://www.haskell.org">Haskell</a> function <code>mconcat</code>: </p> <p> <pre>mconcat :: Monoid a =&gt; [a] -&gt; a</pre> </p> <p> This function, however, seems more limited than it has to be. It says that if you have a linked list of monoidal values, you can reduce them to a single monoidal value. Is this only true for linked lists? </p> <p> After all, in a language like C#, you'd typically express a Composite as a container of 'some collection' of objects, typically modelled by the <code>IReadOnlyCollection&lt;T&gt;</code> interface. There are several implementations of that interface, including lists, arrays, collections, and so on. </p> <p> It seems as though we ought to be able to generalise <code>mconcat</code>, and, indeed, we can. The <code>Data.Foldable</code> module defines a function called <code>fold</code>: </p> <p> <pre>fold :: (Monoid m, Foldable t) =&gt; t m -&gt; m</pre> </p> <p> Let me decipher that for you. It says that any monoid <code>m</code> contained in a 'foldable' container <code>t</code> can be reduced to a single value (still of the type <code>m</code>). You can read <code>t m</code> as 'a foldable container that contains monoids'. In C#, you could attempt to express it as <code>IFoldable&lt;TMonoid&gt;</code>. </p> <p> In other words, the Composite design pattern is equivalent to <code>fold</code>. Here's how it relates to the Null Object pattern: </p> <p> As a first step, consider methods like those defined by the above <code>IController</code> interface. In order to implement <code>NullController</code>, all of those methods ignore their (non-existent) input and return an identity value. In other words, we're looking for a Haskell function of the type <code>Monoid m =&gt; a -&gt; m</code>; that is: a function that takes input of the type <code>a</code> and returns a monoidal value <code>m</code>. </p> <p> You can do that using <code>fold</code>: </p> <p> <pre><span style="color:#600277;">nullify</span>&nbsp;::&nbsp;<span style="color:blue;">Monoid</span>&nbsp;m&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;m nullify&nbsp;<span style="color:#666666;">=</span>&nbsp;fold&nbsp;(<span style="color:#dd0000;">Identity</span>&nbsp;<span style="color:#666666;">$</span>&nbsp;const&nbsp;mempty)</pre> </p> <p> Recall that the input to <code>fold</code> must be a <code>Foldable</code> container. The good old <code>Identity</code> type is, among other capabilities, <code>Foldable</code>. That takes care of the container. The value that we put into the container is a single function that ignores its input (<code>const</code>) and always returns the identity value (<code>mempty</code>). The result is a function that always returns the identity value. </p> <p> This demonstrates that Null Object is a special case of Composite, because <code>nullify</code> is a special application of <code>fold</code>. </p> <p> There's no reason to write <code>nullify</code> in such a complicated way, though. You can simplify it like this: </p> <p> <pre><span style="color:#600277;">nullify</span>&nbsp;::&nbsp;<span style="color:blue;">Monoid</span>&nbsp;m&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;m nullify&nbsp;<span style="color:#666666;">=</span>&nbsp;const&nbsp;mempty</pre> </p> <p> Once you recall, however, that <a href="http://blog.ploeh.dk/2017/11/06/function-monoids">functions are monoids if their return values are monoids</a>, you can simplify it even further: </p> <p> <pre><span style="color:#600277;">nullify</span>&nbsp;::&nbsp;<span style="color:blue;">Monoid</span>&nbsp;m&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;m nullify&nbsp;<span style="color:#666666;">=</span>&nbsp;mempty</pre> </p> <p> The identity element for monoidal functions is exactly a function that ignores its input and returns <code>mempty</code>. </p> <h3 id="11c3a2cefcb74f7096e588c530a699a8"> Controller identity <a href="#11c3a2cefcb74f7096e588c530a699a8" title="permalink">#</a> </h3> <p> Consider the <code>IController</code> interface. According to <a href="http://blog.ploeh.dk/2018/02/12/object-isomorphisms">object isomorphisms</a>, you can represent this interface as a tuple of three functions: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;<span style="color:#dd0000;">Controller</span>&nbsp;<span style="color:#666666;">=</span> &nbsp;&nbsp;(<span style="color:#dd0000;">ControllerState</span>&nbsp;<span style="color:#666666;">-&gt;</span>&nbsp;<span style="color:#dd0000;">Any</span>,&nbsp;<span style="color:#dd0000;">ControllerState</span>&nbsp;<span style="color:#666666;">-&gt;</span>&nbsp;<span style="color:#dd0000;">Any</span>,&nbsp;<span style="color:#dd0000;">ControllerState</span>&nbsp;<span style="color:#666666;">-&gt;</span>&nbsp;<span style="color:blue;">()</span>)</pre> </p> <p> This is cheating a little, because the third tuple element (the one that corresponds to <code>Startup</code>) is <a href="https://en.wikipedia.org/wiki/Pure_function">pure</a>, although I strongly suspect that the intent is that it should mutate the state of the Controller. Two alternatives are to change the function to either <code>ControllerState -&gt; ControllerState</code> or <code>ControllerState -&gt; IO ()</code>, but I'm going to keep things simple. It doesn't change the conclusion. </p> <p> Notice that I've used <code>Any</code> as the return type for the two first tuples. As I've previously covered, Booleans form monoids like <em>any</em> and <em>all</em>. Here, we need to use <code>Any</code>. </p> <p> This tuple is a monoid because all three functions are monoids, and <a href="http://blog.ploeh.dk/2017/10/30/tuple-monoids">a tuple of monoids is itself a monoid</a>. This means that you can easily create a Null Object using <code>mempty</code>: </p> <p> <pre>λ&gt; nullController = mempty :: Controller</pre> </p> <p> The <code>nullController</code> is a triad of functions. You can access them by pattern-matching them, like this: </p> <p> <pre>λ&gt; (isControlWanted, isControlActive, startup) = nullController</pre> </p> <p> Now you can try to call e.g. <code>isControlWanted</code> with various values in order to verify that it always returns false. In this example, I cheated and simply made <code>ControllerState</code> an alias for <code>String</code>: </p> <p> <pre>λ&gt; isControlWanted "foo" Any {getAny = False} λ&gt; isControlWanted "bar" Any {getAny = False}</pre> </p> <p> You'll get similar behaviour from <code>isControlActive</code>, and <code>startup</code> always returns <code>()</code> (<em>unit</em>). </p> <h3 id="e8bd7e04148143039708a179441b7da5"> Relaxation <a href="#e8bd7e04148143039708a179441b7da5" title="permalink">#</a> </h3> <p> As Woolf wrote in the original text, what 'do nothing' means is subjective. I think it's perfectly reasonable to say that monoidal identity fits the description of doing nothing, but you could probably encounter APIs where 'doing nothing' means something else. </p> <p> As an example, consider avatars for online forums, such as Twitter. If you don't supply a picture when you create your profile, you get a default picture. One way to implement such a feature could be by having a 'null' avatar, which is used in place of a proper avatar. Such a default avatar object could (perhaps) be considered a Null Object, but wouldn't necessarily be monoidal. There may not even be a binary operation for avatars. </p> <p> Thus, it's likely that you could encounter or create Null Objects that aren't monoids. That's the reason that I don't claim that a Null Object always is monoidal identity, although I do think that the reverse relationship holds: if it's <em>identity</em>, then it's a Null Object. </p> <h3 id="91d9a7608c884a0d9fe5d01b61d539f5"> Summary <a href="#91d9a7608c884a0d9fe5d01b61d539f5" title="permalink">#</a> </h3> <p> Monoids are associative binary operations with identity. The identity is the value that 'does nothing' in that binary operation, like, for example, <em>0</em> doesn't 'do' anything under addition. Monoids, however, can be more complex than operations on primitive values. Functions, for example, can be monoids as well, as can tuples of functions. </p> <p> The implication of that is that objects can be monoids as well. When you have a monoidal object, then its <em>identity</em> is the 'natural' Null Object. </p> <p> The question was: <em>when can you implement the Null Object pattern?</em> The answer is that you can do that when all involved methods return monoids. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/06/25/visitor-as-a-sum-type">Visitor as a sum type</a>. </p> </div> <div id="comments"> <hr /> <h2 id="comments-header">Comments</h2> <div class="comment" id="37c2c03b75684696bb16afebcbe2458d"> <div class="comment-author"> Ciprian Vilcan </div> <div class="comment-content"> <p> All the examples of using Maybe I recall seeing always wrapped a data type that had a neutral element. So Maybe&lt;int&gt; would resolve to 0 or 1, while Maybe&lt;string&gt; to string.Empty. But what about data types that do not have a neutral element? </p> <p> Suppose we have this DDD value object, NonEmptyString, written in C#. It has no public constructor and it is instantiated through a static factory method that returns a Maybe&lt;NonEmptyString&gt; containing an initialized NonEmptyString if the given input is not null or whitespace and None otherwise. </p> <p> How do you treat the None case when calling the maybe.Match method? Since the neutral element for string concatenation is string.empty, an invalid value for this value object, this type has no possibility of having a Null Object.<br> Can this situation be resolved in the functional way (without throwing an exception) or does it warrant throwing an exception? </p> </div> <div class="comment-date">2018-05-07 08:21 UTC</div> </div> <div class="comment" id="be75b93e68a8441f9bf9cea62a1d94a5"> <div class="comment-author"><a href="http://blog.ploeh.dk">Mark Seemann</a></div> <div class="comment-content"> <p> Ciprian, thank you for writing. I'm not sure I understand what you man by <em>Maybe</em> wrapping a neutral element. I hope that's not how <a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">my introduction to Maybe</a> comes across. Could you point to specific examples? </p> <p> If <code>NonEmptyString</code> is, as the name implies, a <code>string</code> guaranteed to be non-empty, isn't it just a specialisation of <a href="http://blog.ploeh.dk/2017/12/11/semigroups-accumulate/#68b942712506472ebe4c6933ca7dbd56">NotEmptyCollection&lt;T&gt;</a>? If so, indeed, there's no <em>identity</em> for <code>NonEmptyString</code> (but it does form a <a href="http://blog.ploeh.dk/2017/11/27/semigroups">Semigroup</a>). </p> <p> Since it's a semigroup, though, <a href="http://blog.ploeh.dk/2018/04/03/maybe-monoids/#79ed6bcdafca4afd91cd22f6f9cbc4a2">you can lift it to a monoid my wrapping it in Maybe</a>. If you do that, the identity of <code>Maybe&lt;NonEmptyString&gt;</code> would be <em>nothing</em>. </p> </div> <div class="comment-date">2018-05-08 1:53 UTC</div> </div> <div class="comment" id="f78e2713d0634dd39c1674ebcda763dd"> <div class="comment-author"> Ciprian Vilcan </div> <div class="comment-content"> <p> You are right, Mark. The <code>NonEmptyString</code> class is indeed a semigroup, thus has no neutral element. <br> This is not what confuses me, but what function to supply in the None case of a <code>Maybe&lt;SomeSemigroup&gt;</code> when calling the <code>.Match</code> method. In the case of <code>Maybe&lt;SomeMonoid&gt;</code>, it's simple and intuitive, as you simply supply a function that returns the neutral element of that monoid. <br> But what about semigroups? </p> <p> Here's a couple of generalized examples to better illustrate the question I'm having: <br> <code> Maybe&lt;SomeMonoid&gt; firstMaybe = someService.GetSomeMonoid(); <br> SomeMonoid value = firstMaybe.Match(Some: containedValue => containedValue, None: () => SomeMonoid.NeutralElement); <br> <br> Maybe&lt;SomeSemigroup&gt; secondMaybe = someService.GetSomeSemigroup(); <br> SomeSemigroup someSemigroup = secondMaybe.Match(Some: containedValue => containedValue, None: () => /*What to do here? Is it appropriate to throw an exception?*/); </code> </p> <p> I hope this time my question became clearer. I'm still in the process of wrapping my head around functional and category theory concepts, so my terminology may not be pinpoint accurate. </p> </div> <div class="comment-date">2018-05-11 06:44 UTC</div> </div> <div class="comment" id="2cae69987a0443a191f21d1bf4930ab1"> <div class="comment-author"><a href="http://blog.ploeh.dk">Mark Seemann</a></div> <div class="comment-content"> <p> Ciprian, that's the problem with semigroups, isn't it? There's no single natural element to use in the absence of data. </p> <p> Lifting a semigroup to a Maybe is one way to resolve that problem. Since <a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">Maybe is a functor</a>, you can map the contents of the Maybe until you've mapped it into a value for which an identity exists. </p> <p> In some cases, you can also fold a Maybe value by supplying a default value that makes sense in the specific context. A default value can be an appropriate fall-back value in a given context, even if it isn't a general identity. </p> </div> <div class="comment-date">2018-05-12 8:20 UTC</div> </div> <div class="comment" id="9640402dd2834ba0b75d4c1f810dfeaa"> <div class="comment-author"> Ciprian Vilcan </div> <div class="comment-content"> <p> I think I got it!<br> If you want to process that <code>Maybe&lt;SomeSemigroup&gt;</code> in a functional way, using the .Match(Some: ..., None: ...) method, you actually have to transform the method using it from a mostly statement based one, to a mostly expression based one. You have to pretend you don't know what's inside that Maybe for as long as possible, similar to using Lazy (or lazy evaluation in general). </p> <p> In <a href="https://dotnetfiddle.net/8vP47X">this</a> fiddle I've played around and created both an imperative and functional query method for retrieving a book by title and author, in order to prove myself that they can be made isomorphic. These two methods are GetBookFunctional and GetBookImperative.<br> However, I'm now trying to transform the GetBookImperativeWithoutElses into something functional using that .Match method, but I don't think it's possible.<br> The .Match method's signature is, practically speaking, equivalent to the if-else statement, whereas the GetBookImperativeWithoutElses method uses the if statement, meaning the functional approach will be forced to treat the elses, whereas the imperative one won't. </p> <p> Wow, so if you want to use this Maybe of semigroup and/or go fully functional, you really have to go deep down the functional rabbit hole.<br> Also, my guess is there is no guarantee that going from imperative to functional does not introduce more redundancy (like the elses in the second set of methods) into your system.<br> </p> <p> Am I right in these regards? </p> </div> <div class="comment-date">2018-05-12 13:45 UTC</div> </div> <div class="comment" id="fc2325a9be294305916c8bfbdac119bf"> <div class="comment-author"><a href="http://blog.ploeh.dk">Mark Seemann</a></div> <div class="comment-content"> <p> Ciprian, thank you for the link to the code. This explains why you're running into trouble. You absolutely can address the scenario that causes you trouble in a nice functional style, but once you start having the need to keep track of error data as well as happy-path data, <em>Maybe</em> is no longer the data structure you need. </p> <p> <em>Maybe</em> enables you to model a case where data may or may not be available. It enables you distinguish something from nothing. On the other hand, in the absence of data, you have no information about the reason that data is missing. </p> <p> In order to keep track of such information, you need <em>Either</em>, which models data that's either this or that. </p> <p> I'll cover <em>Either</em> in future posts. </p> </div> <div class="comment-date">2018-05-13 14:44 UTC</div> </div> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Endomorphic Composite as a monoid http://blog.ploeh.dk/2018/04/16/endomorphic-composite-as-a-monoid 2018-04-16T08:16:00+00:00 Mark Seemann <div id="post"> <p> <em>A variation of the Composite design pattern uses endomorphic composition. That's still a monoid.</em> </p> <p> This article is part of <a href="http://blog.ploeh.dk/2018/03/05/some-design-patterns-as-universal-abstractions">a series of articles about design patterns and their category theory counterparts</a>. In a <a href="http://blog.ploeh.dk/2018/03/12/composite-as-a-monoid">previous article</a>, you learned that the <a href="https://en.wikipedia.org/wiki/Composite_pattern">Composite</a> design pattern is simply a <a href="http://blog.ploeh.dk/2017/10/06/monoids">monoid</a>. </p> <p> There is, however, a variation of the Composite design pattern where the return value from one step can be used as the input for the next step. </p> <h3 id="e0d1e07a05e14c34aa72e67a2e5fae61"> Endomorphic API <a href="#e0d1e07a05e14c34aa72e67a2e5fae61" title="permalink">#</a> </h3> <p> Imagine that you have to implement some scheduling functionality. For example, you may need to schedule something to happen a month from now, but it should happen on a bank day, during business hours, and you want to know what the resulting date and time will be, expressed in <a href="https://en.wikipedia.org/wiki/Coordinated_Universal_Time">UTC</a>. I've <a href="http://blog.ploeh.dk/2017/11/13/endomorphism-monoid">previously covered the various objects for performing such steps</a>. The common behaviour is this interface: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IDateTimeOffsetAdjustment</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;Adjust(<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;value); }</pre> </p> <p> The <code>Adjust</code> method is an <a href="https://en.wikipedia.org/wiki/Endomorphism">endomorphism</a>; that is: the input type is the same as the return type, in this case <code>DateTimeOffset</code>. A <a href="http://blog.ploeh.dk/2017/11/13/endomorphism-monoid">previous article</a> already established that that's a monoid. </p> <h3 id="24dd8cb072b8434890ddb71fbb5e3ec9"> Composite endomorphism <a href="#24dd8cb072b8434890ddb71fbb5e3ec9" title="permalink">#</a> </h3> <p> If you have various implementations of <code>IDateTimeOffsetAdjustment</code>, you can make a Composite from them, like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">CompositeDateTimeOffsetAdjustment</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IDateTimeOffsetAdjustment</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">IDateTimeOffsetAdjustment</span>&gt;&nbsp;adjustments; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;CompositeDateTimeOffsetAdjustment( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">IDateTimeOffsetAdjustment</span>&gt;&nbsp;adjustments) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(adjustments&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(adjustments)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.adjustments&nbsp;=&nbsp;adjustments; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;Adjust(<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;value) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;acc&nbsp;=&nbsp;value; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">foreach</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;adjustment&nbsp;<span style="color:blue;">in</span>&nbsp;<span style="color:blue;">this</span>.adjustments) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;acc&nbsp;=&nbsp;adjustment.Adjust(acc); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;acc; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> The <code>Adjust</code> method simply starts with the input <code>value</code> and loops over all the composed <code>adjustments</code>. For each <code>adjustment</code> it adjusts <code>acc</code> to produce a new <code>acc</code> value. This goes on until all <code>adjustments</code> have had a chance to adjust the value. </p> <p> Notice that if <code>adjustments</code> is empty, the <code>Adjust</code> method simply returns the input value. In that degenerate case, the behaviour is similar to the identity function, which is the identity for the endomorphism monoid. </p> <p> You can now compose the desired behaviour, as this parametrised <a href="https://xunit.github.io">xUnit.net</a> test demonstrates: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-01-31T07:45:55+2&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;2017-02-28T07:00:00Z&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-02-06T10:03:02+1&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;2017-03-06T09:03:02Z&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-02-09T04:20:00Z&quot;</span>&nbsp;,&nbsp;<span style="color:#a31515;">&quot;2017-03-09T09:00:00Z&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-02-12T16:02:11Z&quot;</span>&nbsp;,&nbsp;<span style="color:#a31515;">&quot;2017-03-10T16:02:11Z&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-03-14T13:48:29-1&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;2017-04-13T14:48:29Z&quot;</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;AdjustReturnsCorrectResult( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;dtS, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;expectedS) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;dt&nbsp;=&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>.Parse(dtS); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;sut&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">CompositeDateTimeOffsetAdjustment</span>( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">NextMonthAdjustment</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">BusinessHoursAdjustment</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">DutchBankDayAdjustment</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">UtcAdjustment</span>()); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;sut.Adjust(dt); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#2b91af;">DateTimeOffset</span>.Parse(expectedS),&nbsp;actual); }</pre> </p> <p> You can see the implementation for all four composed classes in the <a href="http://blog.ploeh.dk/2017/11/13/endomorphism-monoid">previous article</a>. <code>NextMonthAdjustment</code> adjusts a date by a month into its future, <code>BusinessHoursAdjustment</code> adjusts a time to business hours, <code>DutchBankDayAdjustment</code> takes bank holidays and weekends into account in order to return a bank day, and <code>UtcAdjustment</code> convert a date and time to UTC. </p> <h3 id="5743387ec7f94a00861517d399756ab2"> Monoidal accumulation <a href="#5743387ec7f94a00861517d399756ab2" title="permalink">#</a> </h3> <p> As you've learned in that previous article that I've already referred to, an endomorphism is a monoid. In this particular example, the binary operation in question is called <code>Append</code>. From another article, you know that <a href="http://blog.ploeh.dk/2017/11/20/monoids-accumulate">monoids accumulate</a>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">IDateTimeOffsetAdjustment</span>&nbsp;Accumulate( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">IDateTimeOffsetAdjustment</span>&gt;&nbsp;adjustments) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IDateTimeOffsetAdjustment</span>&nbsp;acc&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">IdentityDateTimeOffsetAdjustment</span>(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">foreach</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;adjustment&nbsp;<span style="color:blue;">in</span>&nbsp;adjustments) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;acc&nbsp;=&nbsp;Append(acc,&nbsp;adjustment); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;acc; }</pre> </p> <p> This implementation follows the template previously described: <ul> <li>Initialize a variable <code>acc</code> with the identity element. In this case, the identity is a class called <code>IdentityDateTimeOffsetAdjustment</code>.</li> <li>For each <code>adjustment</code> in <code>adjustments</code>, <code>Append</code> the <code>adjustment</code> to <code>acc</code>.</li> <li>Return <code>acc</code>.</li> </ul> This is an entirely automatable process, and it's only C#'s lack of higher-kinded types that prevents us from writing that code once and for all. In <a href="https://www.haskell.org">Haskell</a>, this general-purpose function exists; it's called <code>mconcat</code>. We'll get back to that in a moment, but first, here's another parametrised unit test that exercises the same test cases as the previous test, only against a composition created by <code>Accumulate</code>: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-01-31T07:45:55+2&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;2017-02-28T07:00:00Z&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-02-06T10:03:02+1&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;2017-03-06T09:03:02Z&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-02-09T04:20:00Z&quot;</span>&nbsp;,&nbsp;<span style="color:#a31515;">&quot;2017-03-09T09:00:00Z&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-02-12T16:02:11Z&quot;</span>&nbsp;,&nbsp;<span style="color:#a31515;">&quot;2017-03-10T16:02:11Z&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;2017-03-14T13:48:29-1&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;2017-04-13T14:48:29Z&quot;</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;AccumulatedAdjustReturnsCorrectResult( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;dtS, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;expectedS) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;dt&nbsp;=&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>.Parse(dtS); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;sut&nbsp;=&nbsp;<span style="color:#2b91af;">DateTimeOffsetAdjustment</span>.Accumulate( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">NextMonthAdjustment</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">BusinessHoursAdjustment</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">DutchBankDayAdjustment</span>(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">UtcAdjustment</span>()); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;sut.Adjust(dt); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(<span style="color:#2b91af;">DateTimeOffset</span>.Parse(expectedS),&nbsp;actual); }</pre> </p> <p> While the implementation is different, this monoidal composition has the same behaviour as the above <code>CompositeDateTimeOffsetAdjustment</code> class. This, again, emphasises that Composites are simply monoids. </p> <h3 id="45b98ea80cb143f2af692a7cd7ac2a4b"> Endo <a href="#45b98ea80cb143f2af692a7cd7ac2a4b" title="permalink">#</a> </h3> <p> For comparison, this section demonstrates how to implement the above behaviour in Haskell. The code here passes the same test cases as those above. You can skip to the next section if you want to get to the conclusion. </p> <p> Instead of classes that implement interfaces, in Haskell you can define functions with the type <code>ZonedTime -&gt; ZonedTime</code>. You can compose such functions using the <code>Endo</code> <code>newtype</code> 'wrapper' that turns endomorphisms into monoids: </p> <p> <pre>λ&gt; adjustments = reverse [adjustToNextMonth, adjustToBusinessHours, adjustToDutchBankDay, adjustToUtc] λ&gt; :type adjustments adjustments :: [ZonedTime -&gt; ZonedTime] λ&gt; adjust = appEndo $ mconcat $ Endo &lt;$&gt; adjustments λ&gt; :type adjust adjust :: ZonedTime -&gt; ZonedTime</pre> </p> <p> In this example, I'm using GHCi (the Haskell REPL) to show the composition in two steps. The first step creates <code>adjustments</code>, which is a list of functions. In case you're wondering about the use of the <code>reverse</code> function, it turns out that <code>mconcat</code> composes from right to left, which I found counter-intuitive in this case. <code>adjustToNextMonth</code> should execute first, followed by <code>adjustToBusinessHours</code>, and so on. Defining the functions in the more intuitive left-to-right direction and then reversing it makes the code easier to understand, I hope. </p> <p> (For the Haskell connoisseurs, you can also achieve the same result by composing <code>Endo</code> with the <code>Dual</code> monoid, instead of reversing the list of adjustments.) </p> <p> The second step composes <code>adjust</code> from <code>adjustments</code>. It first maps <code>adjustments</code> to <code>Endo</code> values. While <code>ZonedTime -&gt; ZonedTime</code> isn't a <code>Monoid</code> instances, <code>Endo ZonedTime</code> is. This means that you can reduce a list of <code>Endo ZonedTime</code> with <code>mconcat</code>. The result is a single <code>Endo ZonedTime</code> value, which you can then unwrap to a function using <code>appEndo</code>. </p> <p> <code>adjust</code> is a function that you can call: </p> <p> <pre>λ&gt; dt 2017-01-31 07:45:55 +0200 λ&gt; adjust dt 2017-02-28 07:00:00 +0000</pre> </p> <p> In this example, I'd already prepared a <code>ZonedTime</code> value called <code>dt</code>. Calling <code>adjust</code> returns a new <code>ZonedTime</code> adjusted by all four composed functions. </p> <h3 id="675b6bd1899746c8963eb97a8580fb24"> Conclusion <a href="#675b6bd1899746c8963eb97a8580fb24" title="permalink">#</a> </h3> <p> In general, you implement the Composite design pattern by calling all composed functions with the original input value, collecting the return value of each call. In the final step, you then reduce the collected return values to a single value that you return. This requires the return type to form a monoid, because otherwise, you can't reduce it. </p> <p> In this article, however, you learned about an alternative implementation of the Composite design pattern. If the method that you compose has the same output type as its input, you can pass the output from one object as the input to the next object. In that case, you can escape the requirement that the return value is a monoid. That's the case with <code>DateTimeOffset</code> and <code>ZonedTime</code>: neither are monoids, because you can't add two dates and times together. </p> <p> At first glance, then, it seems like a falsification of the original claim that Composites are monoids. As you've learned in this article, however, endomorphisms are monoids, so the claim still stands. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/04/23/null-object-as-identity">Null Object as identity</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Coalescing Composite as a monoid http://blog.ploeh.dk/2018/04/09/coalescing-composite-as-a-monoid 2018-04-09T08:15:00+00:00 Mark Seemann <div id="post"> <p> <em>A variation of the Composite design pattern uses coalescing behaviour to return non-composable values. That's still a monoid.</em> </p> <p> This article is part of <a href="http://blog.ploeh.dk/2018/03/05/some-design-patterns-as-universal-abstractions">a series of articles about design patterns and their category theory counterparts</a>. In <a href="http://blog.ploeh.dk/2018/03/12/composite-as-a-monoid">a previous article</a>, you learned that the <a href="https://en.wikipedia.org/wiki/Composite_pattern">Composite</a> design pattern is simply a <a href="http://blog.ploeh.dk/2017/10/06/monoids">monoid</a>. </p> <h3 id="ee5e76abfc9c4fe58a5e232579e397c5"> Monoidal return types <a href="#ee5e76abfc9c4fe58a5e232579e397c5" title="permalink">#</a> </h3> <p> When all methods of an interface return monoids, you can create a Composite. This is fairly intuitive once you understand what a monoid is. Consider this example interface: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">ICustomerRepository</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">void</span>&nbsp;Create(<span style="color:#2b91af;">Customer</span>&nbsp;customer); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Customer</span>&nbsp;Read(<span style="color:#2b91af;">Guid</span>&nbsp;id); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">void</span>&nbsp;Update(<span style="color:#2b91af;">Customer</span>&nbsp;customer); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">void</span>&nbsp;Delete(<span style="color:#2b91af;">Guid</span>&nbsp;id); }</pre> </p> <p> While this interface is, in fact, not readily composable, most of the methods are. It's easy to compose the three <code>void</code> methods. Here's a composition of the <code>Create</code> method: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;Create(<span style="color:#2b91af;">Customer</span>&nbsp;customer) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">foreach</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;repository&nbsp;<span style="color:blue;">in</span>&nbsp;<span style="color:blue;">this</span>.repositories) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;repository.Create(customer); }</pre> </p> <p> In this case it's easy to compose multiple repositories, because <code>void</code> (<a href="http://blog.ploeh.dk/2018/01/15/unit-isomorphisms">or, rather, <em>unit</em></a>) forms a monoid. If you have methods that return numbers, you can add the numbers together (a monoid). If you have methods that return strings, you can concatenate the strings (a monoid). If you have methods that return Boolean values, you can <em>or</em> or <em>and</em> them together (more monoids). </p> <p> What about the above <code>Read</code> method, though? </p> <h3 id="05eec84ac1514c10bdbb0dbc6b36a957"> Picking the first Repository <a href="#05eec84ac1514c10bdbb0dbc6b36a957" title="permalink">#</a> </h3> <p> Why would you even want to compose two repositories? One scenario is where you have an old data store, and you want to move to a new data store. For a while, you wish to write to both data stores, but one of them stays the 'primary' data store, so this is the one from which you read. </p> <p> Imagine that the old repository saves customer information as JSON files on disk. The new data store, on the other hand, saves customer data as JSON documents in <a href="https://azure.microsoft.com/en-us/services/storage/blobs">Azure Blob Storage</a>. You've already written two implementations of <code>ICustomerRepository</code>: <code>FileCustomerRepository</code> and <code>AzureCustomerRepository</code>. How do you compose them? </p> <p> The three methods that return <code>void</code> are easy, as the above <code>Create</code> implementation demonstrates. The <code>Read</code> method, however, is more tricky. </p> <p> One option is to only query the first repository, and return its return value: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Customer</span>&nbsp;Read(<span style="color:#2b91af;">Guid</span>&nbsp;id) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.repositories.First().Read(id); }</pre> </p> <p> This works, but doesn't generalise. It works if you know that you have a non-empty collection of repositories, but if you want to adhere to the <a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle">Liskov Substitution Principle</a>, you should be able to handle the case where there's no repositories. </p> <p> A Composite should be able to compose an arbitrary number of other objects. This includes a collection of no objects. The <code>CompositeCustomerRepository</code> class has this constructor: </p> <p> <pre><span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">ICustomerRepository</span>&gt;&nbsp;repositories; <span style="color:blue;">public</span>&nbsp;CompositeCustomerRepository( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">ICustomerRepository</span>&gt;&nbsp;repositories) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(repositories&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(repositories)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.repositories&nbsp;=&nbsp;repositories; }</pre> </p> <p> It uses standard Constructor Injection to inject an <code>IReadOnlyCollection&lt;ICustomerRepository&gt;</code>. Such a collection is finite, but can be empty. </p> <p> Another problem with blindly returning the value from the first repository is that the return value may be empty. </p> <p> In C#, people often use <code>null</code> to indicate a missing value, and while I find such practice unwise, I'll pursue this option for a bit. </p> <p> A more robust Composite would return the first non-null value it gets: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Customer</span>&nbsp;Read(<span style="color:#2b91af;">Guid</span>&nbsp;id) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">foreach</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;repository&nbsp;<span style="color:blue;">in</span>&nbsp;<span style="color:blue;">this</span>.repositories) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;customer&nbsp;=&nbsp;repository.Read(id); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(customer&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;customer; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">null</span>; }</pre> </p> <p> This implementation loops through all the injected <code>repositories</code> and calls <code>Read</code> on each until it gets a result that is not <code>null</code>. This will often be the first value, but doesn't have to be. If all repositories return <code>null</code>, then the Composite also returns <code>null</code>. To emphasise my position, I would never design C# code like this, but at least it's consistent. </p> <p> If you've ever worked with relational databases, you may have had an opportunity to use the <code>COALESCE</code> function, which works in exactly the same way. This is the reason I call such an implementation a <em>coalescing Composite</em>. </p> <h3 id="ae3e089ecda84bd299e44c22554f5b85"> The First monoid <a href="#ae3e089ecda84bd299e44c22554f5b85" title="permalink">#</a> </h3> <p> The <a href="https://docs.microsoft.com/en-us/sql/t-sql/language-elements/coalesce-transact-sql">T-SQL documentation for COALESCE</a> describes the operation like this: <blockquote> "Evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to <code>NULL</code>." </blockquote> The <a href="https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions023.htm#SQLRF00617">Oracle documentation</a> expresses it as: <blockquote> "<code>COALESCE</code> returns the first non-null <code>expr</code> in the expression list." </blockquote> This may not be apparent, but that's a monoid. </p> <p> <a href="https://www.haskell.org">Haskell</a>'s base library comes with a monoidal type called <code>First</code>, which is a <blockquote> "Maybe monoid returning the leftmost non-Nothing value." </blockquote> Sounds familiar? </p> <p> Here's how you can use it in GHCi: </p> <p> <pre>λ&gt; First (Just (Customer id1 "Joan")) &lt;&gt; First (Just (Customer id2 "Nigel")) First {getFirst = Just (Customer {customerId = 1243, customerName = "Joan"})} λ&gt; First (Just (Customer id1 "Joan")) &lt;&gt; First Nothing First {getFirst = Just (Customer {customerId = 1243, customerName = "Joan"})} λ&gt; First Nothing &lt;&gt; First (Just (Customer id2 "Nigel")) First {getFirst = Just (Customer {customerId = 5cd5, customerName = "Nigel"})} λ&gt; First Nothing &lt;&gt; First Nothing First {getFirst = Nothing}</pre> </p> <p> (To be clear, the above examples uses <code>First</code> from <code>Data.Monoid</code>, not <code>First</code> from <code>Data.Semigroup</code>.) </p> <p> The operator <code>&lt;&gt;</code> is an infix alias for <code>mappend</code> - Haskell's polymorphic binary operation. </p> <p> As long as the left-most value is present, that's the return value, regardless of whether the right value is <code>Just</code> or <code>Nothing</code>. Only when the left value is <code>Nothing</code> is the right value returned. Notice that this value may also be <code>Nothing</code>, causing the entire expression to be <code>Nothing</code>. </p> <p> That's exactly the same behaviour as the above implementation of the <code>Read</code> method. </p> <h3 id="c83d6ec43ba94073b151841289050fba"> First in C# <a href="#c83d6ec43ba94073b151841289050fba" title="permalink">#</a> </h3> <p> It's easy to port Haskell's <code>First</code> type to C#: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">First</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;item; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;hasItem; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;First() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.hasItem&nbsp;=&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;First(<span style="color:#2b91af;">T</span>&nbsp;item) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(item&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(item)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.item&nbsp;=&nbsp;item; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.hasItem&nbsp;=&nbsp;<span style="color:blue;">true</span>; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">First</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;FindFirst(<span style="color:#2b91af;">First</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;other) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(<span style="color:blue;">this</span>.hasItem) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">else</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;other; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Instead of nesting <code>Maybe</code> inside of <code>First</code>, as Haskell does, I simplified a bit and gave <code>First&lt;T&gt;</code> two constructor overloads: one that takes a value, and one that doesn't. The <code>FindFirst</code> method is the binary operation that corresponds to Haskell's <code>&lt;&gt;</code> or <code>mappend</code>. </p> <p> This is only one of several alternative implementations of <a href="http://blog.ploeh.dk/2018/04/03/maybe-monoids">the <em>first</em> monoid</a>. </p> <p> In order to make <code>First&lt;T&gt;</code> a monoid, it must also have an identity, which is just an empty value: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">First</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;Identity&lt;<span style="color:#2b91af;">T</span>&gt;() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">First</span>&lt;<span style="color:#2b91af;">T</span>&gt;(); }</pre> </p> <p> This enables you to <a href="http://blog.ploeh.dk/2017/11/20/monoids-accumulate">accumulate</a> an arbitrary number of <code>First&lt;T&gt;</code> values to a single value: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">First</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;Accumulate&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">IReadOnlyList</span>&lt;<span style="color:#2b91af;">First</span>&lt;<span style="color:#2b91af;">T</span>&gt;&gt;&nbsp;firsts) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;acc&nbsp;=&nbsp;Identity&lt;<span style="color:#2b91af;">T</span>&gt;(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">foreach</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;first&nbsp;<span style="color:blue;">in</span>&nbsp;firsts) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;acc&nbsp;=&nbsp;acc.FindFirst(first); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;acc; }</pre> </p> <p> You start with the identity, which is also the return value if <code>firsts</code> is empty. If that's not the case, you loop through all <code>firsts</code> and update <code>acc</code> by calling <code>FindFirst</code>. </p> <h3 id="d90234ded89e483bbc6eb8db9ffb0a19"> A composable Repository <a href="#d90234ded89e483bbc6eb8db9ffb0a19" title="permalink">#</a> </h3> <p> You can formalise such a design by changing the <code>ICustomerRepository</code> interface: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">ICustomerRepository</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">void</span>&nbsp;Create(<span style="color:#2b91af;">Customer</span>&nbsp;customer); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">First</span>&lt;<span style="color:#2b91af;">Customer</span>&gt;&nbsp;Read(<span style="color:#2b91af;">Guid</span>&nbsp;id); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">void</span>&nbsp;Update(<span style="color:#2b91af;">Customer</span>&nbsp;customer); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">void</span>&nbsp;Delete(<span style="color:#2b91af;">Guid</span>&nbsp;id); }</pre> </p> <p> In this modified version, <code>Read</code> explicitly returns <code>First&lt;Customer&gt;</code>. The rest of the methods remain as before. </p> <p> The reusable API of <code>First</code> makes it easy to implement a Composite version of <code>Read</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">First</span>&lt;<span style="color:#2b91af;">Customer</span>&gt;&nbsp;Read(<span style="color:#2b91af;">Guid</span>&nbsp;id) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;candidates&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">First</span>&lt;<span style="color:#2b91af;">Customer</span>&gt;&gt;(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">foreach</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;repository&nbsp;<span style="color:blue;">in</span>&nbsp;<span style="color:blue;">this</span>.repositories) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;candidates.Add(repository.Read(id)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">First</span>.Accumulate(candidates); }</pre> </p> <p> You could argue that this seems to be wasteful, because it calls <code>Read</code> on all repositories. If the first Repository returns a value, all remaining queries are wasted. You can address that issue with lazy evaluation. </p> <p> You can see (a recording of) a live demo of the example in this article in my <a href="https://cleancoders.com">Clean Coders</a> video <a href="https://cleancoders.com/episode/humane-code-real-episode-2/show">Composite as Universal Abstraction</a>. </p> <h3 id="8c301e16ccf34fd099e4f97503c005c5"> Summary <a href="#8c301e16ccf34fd099e4f97503c005c5" title="permalink">#</a> </h3> <p> While the typical Composite is implemented by directly aggregating the return values from the composed objects, variations exist. One variation picks the first non-empty value from a collection of candidates, reminiscent of the SQL <code>COALESCE</code> function. This is, however, still a monoid, so the overall conjecture that Composites are monoids still holds. </p> <p> Another Composite variation exists, but that one turns out to be a monoid as well. Read on! </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/04/16/endomorphic-composite-as-a-monoid">Endomorphic Composite as a monoid</a>. </p> </div> <div id="comments"> <hr> <h2 id="comments-header">Comments</h2> <div class="comment" id="d5cb5c03f4af4f70928674c774f09058"> <div class="comment-author"><a href="http://www.nikolamilekic.com">Nikola Milekic</a></div> <div class="comment-content"> <blockquote>When all methods of an interface return monoids, you can create a Composite. This is fairly intuitive once you understand what a monoid is.</blockquote> <p> I've been struggling a bit with the terminology and I could use a bit of help. </p> <p> I understand a <code>Monoid&lt;a&gt;</code> to be of type <code>a -> a -> a</code>. I further understand that it can be said that <code>a</code> "forms a monoid over" the specific <code>a -> a -> a</code> implementation. We can then say that an int forms two different monoids over addition and multiplication. </p> <p> Is my understanding above accurate and if so wouldn't it be more accurate to say that you can create a composite from an interface only when all of its methods <em>return values that form monoids</em>? Saying that they have to return monoids (instead of values that form them) goes against my understanding that a monoid is a binary operation. </p> <p> Thanks a lot for an amazing article series, and for this blog overall. Keep up the good work! </p> </div> <div class="comment-date">2018-08-07 21:04 UTC</div> </div> <div class="comment" id="de5c75b6e2374a03bb3301cd670b9720"> <div class="comment-author"><a href="http://blog.ploeh.dk">Mark Seemann</a></div> <div class="comment-content"> <p> Nikola, thank you for writing. You're correct: it <em>would</em> be more correct to say that you can create a Composite from an interface when all of its methods return types that form monoids. Throughout this article series, I've been struggling to keep my language as correct and specific as possible, but I sometimes slip up. </p> <p> This has come up before, so perhaps you'll find <a href="http://blog.ploeh.dk/2017/10/30/tuple-monoids#68cbe481b0e74c3284e45d4e8dd51da4">this answer</a> helpful. </p> <p> By the way, there's one exception to the rule that in order to be able to create a Composite, all methods must return types that form monoids. This is <a href="http://blog.ploeh.dk/2018/04/16/endomorphic-composite-as-a-monoid">when the return type is the same as the input type</a>. The resulting Composite is still a monoid, so the overall conclusion holds. </p> </div> <div class="comment-date">2018-08-08 6:32 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Maybe monoids http://blog.ploeh.dk/2018/04/03/maybe-monoids 2018-04-03T12:58:00+00:00 Mark Seemann <div id="post"> <p> <em>You can combine Maybe objects in several ways. An article for object-oriented programmers.</em> </p> <p> This article is part of a <a href="http://blog.ploeh.dk/2017/10/06/monoids">series about monoids</a>. In short, a monoid is an associative binary operation with a neutral element (also known as identity). </p> <p> You can combine <a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">Maybe</a> objects in various ways, thereby turning them into monoids. There's at least two unconstrained monoids over Maybe values, as well as some constrained monoids. By <em>constrained</em> I mean that the monoid only exists for Maybe objects that contain certain values. You'll see such an example first. </p> <h3 id="7a7573db11bf4e73b49aa84b7c9d1253"> Combining Maybes over semigroups <a href="#7a7573db11bf4e73b49aa84b7c9d1253" title="permalink">#</a> </h3> <p> If you have two Maybe objects, and they both (potentially) contain values that form a <a href="http://blog.ploeh.dk/2017/11/27/semigroups">semigroup</a>, you can combine the Maybe values as well. Here's a few examples. </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;CombineMinimum(<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(x.HasItem&nbsp;&amp;&amp;&nbsp;y.HasItem) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">int</span>&gt;(<span style="color:#2b91af;">Math</span>.Min(x.Item,&nbsp;y.Item)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(x.HasItem) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;y; }</pre> </p> <p> In this first example, the semigroup operation in question is the <em>minimum</em> operation. Since C# doesn't enable you to write generic code over mathematical operations, the above method just gives you an example implemented for <code>Maybe&lt;int&gt;</code> values. If you also want to support e.g. <code>Maybe&lt;decimal&gt;</code> or <code>Maybe&lt;long&gt;</code>, you'll have to add overloads for those types. </p> <p> If both <code>x</code> and <code>y</code> have values, you get the minimum of those, still wrapped in a Maybe container: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;x&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">int</span>&gt;(42); <span style="color:blue;">var</span>&nbsp;y&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">int</span>&gt;(1337); <span style="color:blue;">var</span>&nbsp;m&nbsp;=&nbsp;<span style="color:#2b91af;">Maybe</span>.CombineMinimum(x,&nbsp;y);</pre> </p> <p> Here, <code>m</code> is a <code>new Maybe&lt;int&gt;(42)</code>. </p> <p> It's possible to combine any two Maybe objects as long as you have a way to combine the contained values in the case where both Maybe objects contain values. In other words, you need a binary operation, so the contained values must form a semigroup, like, for example, the <em>minimum</em> operation. Another example is <em>maximum:</em> </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">decimal</span>&gt;&nbsp;CombineMaximum(<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">decimal</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">decimal</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(x.HasItem&nbsp;&amp;&amp;&nbsp;y.HasItem) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">decimal</span>&gt;(<span style="color:#2b91af;">Math</span>.Max(x.Item,&nbsp;y.Item)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(x.HasItem) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;y; }</pre> </p> <p> In order to vary the examples, I chose to implement this operation for <code>decimal</code> instead of <code>int</code>, but you can see that the implementation code follows the same template. When both <code>x</code> and <code>y</code> contains values, you invoke the binary operation. If, on the other hand, <code>y</code> is empty, then right identity still holds: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;x&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">decimal</span>&gt;(42); <span style="color:blue;">var</span>&nbsp;y&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">decimal</span>&gt;(); <span style="color:blue;">var</span>&nbsp;m&nbsp;=&nbsp;<span style="color:#2b91af;">Maybe</span>.CombineMaximum(x,&nbsp;y);</pre> </p> <p> Since <code>y</code> in the above example is empty, the resulting object <code>m</code> is a <code>new Maybe&lt;decimal&gt;(42)</code>. </p> <p> You don't have to constrain yourself to semigroups exclusively. You can use a monoid as well, such as the <em>sum</em> monoid: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">long</span>&gt;&nbsp;CombineSum(<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">long</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">long</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(x.HasItem&nbsp;&amp;&amp;&nbsp;y.HasItem) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">long</span>&gt;(x.Item&nbsp;+&nbsp;y.Item); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(x.HasItem) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;y; }</pre> </p> <p> Again, notice how most of this code is boilerplate code that follows the same template as above. In C#, unfortunately, you have to write out all the combinations of operations and contained types, but in <a href="https://www.haskell.org">Haskell</a>, with its stronger type system, it all comes in the base library: </p> <p> <pre>Prelude Data.Semigroup&gt; Option (Just (Min 42)) &lt;&gt; Option (Just (Min 1337)) Option {getOption = Just (Min {getMin = 42})} Prelude Data.Semigroup&gt; Option (Just (Max 42)) &lt;&gt; mempty Option {getOption = Just (Max {getMax = 42})} Prelude Data.Semigroup&gt; mempty &lt;&gt; Option (Just (Sum 1337)) Option {getOption = Just (Sum {getSum = 1337})}</pre> </p> <p> That particular monoid over Maybe, however, does require as a minimum that the contained values form a semigroup. There are other monoids over Maybe that don't have any such constraints. </p> <h3 id="a21e44f2039d440f9e9469770a47777e"> First <a href="#a21e44f2039d440f9e9469770a47777e" title="permalink">#</a> </h3> <p> As you can read in <a href="http://blog.ploeh.dk/2017/11/27/semigroups">the introductory article about semigroups</a>, there's two semigroup operations called <em>first</em> and <em>last</em>. Similarly, there's two operations by the same name defined over monoids. They behave a little differently, although they're related. </p> <p> The <em>first</em> monoid operation <em>returns the left-most non-empty value</em> among candidates. You can view <em>nothing</em> as being a <a href="http://blog.ploeh.dk/2015/11/13/null-has-no-type-but-maybe-has">type-safe equivalent to null</a>, in which case this monoid is equivalent to a <a href="https://en.wikipedia.org/wiki/Null_coalescing_operator">null coalescing operator</a>. </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;First&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(x.HasItem) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;y; }</pre> </p> <p> As long as <code>x</code> contains a value, <code>First</code> returns it. The contained values don't have to form monoids or semigroups, as this example demonstrates: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;x&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">Guid</span>&gt;(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Guid</span>(<span style="color:#a31515;">&quot;03C2ECDBEF1D46039DE94A9994BA3C1E&quot;</span>)); <span style="color:blue;">var</span>&nbsp;y&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">Guid</span>&gt;(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Guid</span>(<span style="color:#a31515;">&quot;A1B7BC82928F4DA892D72567548A8826&quot;</span>)); <span style="color:blue;">var</span>&nbsp;m&nbsp;=&nbsp;<span style="color:#2b91af;">Maybe</span>.First(x,&nbsp;y);</pre> </p> <p> While I'm not aware of any reasonable way to combine <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">GUIDs</a>, you can still pick the left-most non-empty value. In the above example, <code>m</code> contains <code>03C2ECDBEF1D46039DE94A9994BA3C1E</code>. If, on the other hand, the first value is empty, you get a different result: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;x&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">Guid</span>&gt;(); <span style="color:blue;">var</span>&nbsp;y&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">Guid</span>&gt;(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Guid</span>(<span style="color:#a31515;">&quot;2A2D19DE89D84EFD9E5BEE7C4ADAFD90&quot;</span>)); <span style="color:blue;">var</span>&nbsp;m&nbsp;=&nbsp;<span style="color:#2b91af;">Maybe</span>.First(x,&nbsp;y);</pre> </p> <p> In this case, <code>m</code> contains <code>2A2D19DE89D84EFD9E5BEE7C4ADAFD90</code>, even though it comes from <code>y</code>. </p> <p> Notice that there's no guarantee that <code>First</code> returns a non-empty value. If both <code>x</code> and <code>y</code> are empty, then the result is also empty. The <code>First</code> operation is an associative binary operation, and the identity is the empty value (often called <em>nothing</em> or <em>none</em>). It's a monoid. </p> <h3 id="119e8d969d5e4f35a47c6c17947a28f9"> Last <a href="#119e8d969d5e4f35a47c6c17947a28f9" title="permalink">#</a> </h3> <p> Since you can define a binary operation called <code>First</code>, it's obvious that you can also define one called <code>Last</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;Last&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(y.HasItem) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;y; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;x; }</pre> </p> <p> This operation <em>returns the right-most non-empty value</em>: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;x&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">Guid</span>&gt;(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Guid</span>(<span style="color:#a31515;">&quot;1D9326CDA0B3484AB495DFD280F990A3&quot;</span>)); <span style="color:blue;">var</span>&nbsp;y&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">Guid</span>&gt;(<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Guid</span>(<span style="color:#a31515;">&quot;FFFC6CE263C7490EA0290017FE02D9D4&quot;</span>)); <span style="color:blue;">var</span>&nbsp;m&nbsp;=&nbsp;<span style="color:#2b91af;">Maybe</span>.Last(x,&nbsp;y);</pre> </p> <p> In this example, <code>m</code> contains <code>FFFC6CE263C7490EA0290017FE02D9D4</code>, but while <code>Last</code> favours <code>y</code>, it'll still return <code>x</code> if <code>y</code> is empty. Notice that, like <code>First</code>, there's no guarantee that you'll receive a populated Maybe. If both <code>x</code> and <code>y</code> are empty, the result will be empty as well. </p> <p> Like <code>First</code>, <code>Last</code> is an associative binary operation with <em>nothing</em> as the identity. </p> <h3 id="79ed6bcdafca4afd91cd22f6f9cbc4a2"> Generalisation <a href="#79ed6bcdafca4afd91cd22f6f9cbc4a2" title="permalink">#</a> </h3> <p> The first examples you saw in this article (<code>CombineMinimum</code>, <code>CombineMaximum</code>, and so on), came with the constraint that the contained values form a semigroup. The <code>First</code> and <code>Last</code> operations, on the other hand, seem unconstrained. They work even on GUIDs, which notoriously can't be combined. </p> <p> If you recall, though, <em>first</em> and <em>last</em> are both associative binary operations. They are, in fact, unconstrained semigroups. Recall the <code>Last</code> semigroup: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Last&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">T</span>&nbsp;x,&nbsp;<span style="color:#2b91af;">T</span>&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;y; }</pre> </p> <p> This binary operation operates on any unconstrained type <code>T</code>, including <code>Guid</code>. It unconditionally returns <code>y</code>. </p> <p> You could implement the <code>Last</code> monoid over Maybe using the same template as above, utilising the underlying semigroup: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;Last&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;x,&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;y) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(x.HasItem&nbsp;&amp;&amp;&nbsp;y.HasItem) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;(Last(x.Item,&nbsp;y.Item)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(x.HasItem) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;y; }</pre> </p> <p> This implementation has exactly the same behaviour as the previous implementation of <code>Last</code> shown earlier. You can implement <code>First</code> in the same way. </p> <p> That's exactly how Haskell works: </p> <p> <pre>Prelude Data.Semigroup Data.UUID.Types&gt; x = sequence $ Last $ fromString "03C2ECDB-EF1D-4603-9DE9-4A9994BA3C1E" Prelude Data.Semigroup Data.UUID.Types&gt; x Just (Last {getLast = 03c2ecdb-ef1d-4603-9de9-4a9994ba3c1e}) Prelude Data.Semigroup Data.UUID.Types&gt; y = sequence $ Last $ fromString "A1B7BC82-928F-4DA8-92D7-2567548A8826" Prelude Data.Semigroup Data.UUID.Types&gt; y Just (Last {getLast = a1b7bc82-928f-4da8-92d7-2567548a8826}) Prelude Data.Semigroup Data.UUID.Types&gt; Option x &lt;&gt; Option y Option {getOption = Just (Last {getLast = a1b7bc82-928f-4da8-92d7-2567548a8826})} Prelude Data.Semigroup Data.UUID.Types&gt; Option x &lt;&gt; mempty Option {getOption = Just (Last {getLast = 03c2ecdb-ef1d-4603-9de9-4a9994ba3c1e})}</pre> </p> <p> The <code>&lt;&gt;</code> operator is the generic binary operation, and the way Haskell works, it changes behaviour depending on the type upon which it operates. <code>Option</code> is a wrapper around <code>Maybe</code>, and <code>Last</code> represents the <em>last</em> semigroup. When you stack <code>UUID</code> values inside of <code>Option Last</code>, you get the behaviour of selecting the right-most non-empty value. </p> <p> In fact, <blockquote> <a href="https://en.wikipedia.org/wiki/Monoid">Any semigroup <em>S</em> may be turned into a monoid simply by adjoining an element <em>e</em> not in <em>S</em> and defining <em>e</em> • <em>s</em> = <em>s</em> = <em>s</em> • <em>e</em> for all <em>s</em> ∈ <em>S</em>.</a> </blockquote> </p> <p> <img src="/content/binary/semigroup-to-monoid.png" alt="semigroup-to-monoid diagram"> </p> <p> That's just a mathematical way of saying that if you have a semigroup, you can add an extra value <em>e</em> and make <em>e</em> behave like the identity for the monoid you're creating. That extra value is <em>nothing</em>. The way Haskell's <code>Data.Semigroup</code> module models a monoid over Maybe instances aligns with the underlying mathematics. </p> <h3 id="908819d511be489e8f02f7751b666804"> Conclusion <a href="#908819d511be489e8f02f7751b666804" title="permalink">#</a> </h3> <p> Just as there's more than one monoid over numbers, and more than one monoid over Boolean values, there's more than one monoid over Maybe values. The most useful one may be the one that elevates any semigroup to a monoid by adding <em>nothing</em> as the identity, but others exist. While, at first glance, the <em>first</em > and <em>last</em> monoids over Maybes look like operations in their own right, they're just applications of the general rule. They elevate the <em>first</em> and <em>last</em> semigroups to monoids by 'wrapping' them in Maybes, and using <em>nothing</em> as the identity. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2017/11/20/monoids-accumulate">Monoids accumulate</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. The Maybe functor http://blog.ploeh.dk/2018/03/26/the-maybe-functor 2018-03-26T05:19:00+00:00 Mark Seemann <div id="post"> <p> <em>A introduction to the Maybe functor for object-oriented programmers.</em> </p> <p> This article is an instalment in <a href="http://blog.ploeh.dk/2018/03/22/functors">an article series about functors</a>. </p> <p> One of the simplest, and easiest to understand, functors is <em>Maybe</em>. It's also sometimes known as the <em>Maybe monad</em>, but this is not a monad tutorial; it's a functor tutorial. Maybe is many things; one of them is a functor. In <a href="http://fsharp.org">F#</a>, Maybe is called <code>option</code>. </p> <h3 id="e9a74dc1e498466a9f8bf63224867176"> Motivation <a href="#e9a74dc1e498466a9f8bf63224867176" title="permalink">#</a> </h3> <p> Maybe enables you to model a value that may or may not be present. Object-oriented programmers typically have a hard time grasping the significance of Maybe, since it essentially does the same as <em>null</em> in mainstream object-oriented languages. There are differences, however. In languages like C# and Java, most things can be null, which can lead to much <a href="http://blog.ploeh.dk/2013/07/08/defensive-coding">defensive coding</a>. What happens more frequently, though, is that programmers forget to check for null, with run-time exceptions as the result. </p> <p> A Maybe value, on the other hand, makes it explicit that a value may or may not be present. In statically typed languages, it also forces you to deal with the case where no data is present; if you don't, your code will not compile. </p> <p> Finally, in a language like C#, <a href="http://blog.ploeh.dk/2015/11/13/null-has-no-type-but-maybe-has">null has no type</a>, but a Maybe value always has a type. </p> <p> If you appreciate the tenet that <a href="https://www.python.org/dev/peps/pep-0020">explicit is better than implicit</a>, then you should favour Maybe over null. </p> <h3 id="09da3571d64a4a77b94ffccacd59e3ed"> Implementation <a href="#09da3571d64a4a77b94ffccacd59e3ed" title="permalink">#</a> </h3> <p> If you've read <a href="http://blog.ploeh.dk/2018/03/22/functors">the introduction</a>, then you know that <code>IEnumerable&lt;T&gt;</code> is a functor. In many ways, Maybe is like <code>IEnumerable&lt;T&gt;</code>, but it's a particular type of collection that can only contain zero or one element(s). There are various ways in which you can implement Maybe in an object-oriented language like C#; here's one: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">internal</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;HasItem&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">internal</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Item&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Maybe() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.HasItem&nbsp;=&nbsp;<span style="color:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Maybe(<span style="color:#2b91af;">T</span>&nbsp;item) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(item&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(item)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.HasItem&nbsp;=&nbsp;<span style="color:blue;">true</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.Item&nbsp;=&nbsp;item; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;Select&lt;<span style="color:#2b91af;">TResult</span>&gt;(<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;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(selector&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(selector)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(<span style="color:blue;">this</span>.HasItem) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;(selector(<span style="color:blue;">this</span>.Item)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">else</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;(); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;GetValueOrFallback(<span style="color:#2b91af;">T</span>&nbsp;fallbackValue) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(fallbackValue&nbsp;==&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:blue;">nameof</span>(fallbackValue)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(<span style="color:blue;">this</span>.HasItem) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.Item; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">else</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;fallbackValue; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;Equals(<span style="color:blue;">object</span>&nbsp;obj) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;other&nbsp;=&nbsp;obj&nbsp;<span style="color:blue;">as</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(other&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:blue;">false</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">object</span>.Equals(<span style="color:blue;">this</span>.Item,&nbsp;other.Item); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">int</span>&nbsp;GetHashCode() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.HasItem&nbsp;?&nbsp;<span style="color:blue;">this</span>.Item.GetHashCode()&nbsp;:&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> This is a generic class with two constructors. The parameterless constructor indicates the case where no value is present, whereas the other constructor overload indicates the case where exactly one value is available. Notice that a guard clause prevents you from accidentally passing null as a value. </p> <p> The <code>Select</code> method has the correct signature for a functor. If a value is present, it uses the <code>selector</code> method argument to map <code>item</code> to a new value, and return a new <code>Maybe&lt;TResult&gt;</code> value. If no value is available, then a new empty <code>Maybe&lt;TResult&gt;</code> value is returned. </p> <p> This class also override <code>Equals</code>. This isn't necessary in order for it to be a functor, but it makes it easier to compare two <code>Maybe&lt;T&gt;</code> values. </p> <p> A common question about such generic <a href="https://bartoszmilewski.com/2014/01/14/functors-are-containers">containers</a> is: <em>how do you get the value out of the container?</em> </p> <p> The answer depends on the particular container, but in this example, I decided to enable that functionality with the <code>GetValueOrFallback</code> method. The only way to get the item out of a <code>Maybe</code> value is by supplying a fall-back value that can be used if no value is available. This is one way to guarantee that you, as a client developer, always remember to deal with the empty case. </p> <h3 id="b95ee3d38a35472c949b3cea4c5b0216"> Usage <a href="#b95ee3d38a35472c949b3cea4c5b0216" title="permalink">#</a> </h3> <p> It's easy to use this <code>Maybe</code> class: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;source&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">int</span>&gt;(42); </pre> </p> <p> This creates a new <code>Maybe&lt;int&gt;</code> object that contains the value <code>42</code>. If you need to change the value inside the object, you can, for example, do this: </p> <p> <pre><span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;dest&nbsp;=&nbsp;source.Select(x&nbsp;=&gt;&nbsp;x.ToString()); </pre> </p> <p> Since C# natively understands functors through its query syntax, you could also have written the above translation like this: </p> <p> <pre><span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;dest&nbsp;=&nbsp;<span style="color:blue;">from</span>&nbsp;x&nbsp;<span style="color:blue;">in</span>&nbsp;source &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;x.ToString();</pre> </p> <p> It's up to you and your collaborators whether you prefer one or the other of those alternatives. In both examples, though, <code>dest</code> is a new populated <code>Maybe&lt;string&gt;</code> object containing the string <code>"42"</code>. </p> <p> A more realistic example could be as part of a line-of-business application. Many <a href="http://blog.ploeh.dk/2012/12/18/RangersandZookeepers">enterprise developers</a> are familiar with the <a href="https://martinfowler.com/eaaCatalog/repository.html">Repository pattern</a>. Imagine that you'd like to query a repository for a <code>Reservation</code> object. If one is found in the database, you'd like to convert it to a view model, so that you can display it. </p> <p> <pre><span style="color:blue;">var</span>&nbsp;viewModel&nbsp;=&nbsp;repository.Read(id) &nbsp;&nbsp;&nbsp;&nbsp;.Select(r&nbsp;=&gt;&nbsp;r.ToViewModel()) &nbsp;&nbsp;&nbsp;&nbsp;.GetValueOrFallback(<span style="color:#2b91af;">ReservationViewModel</span>.Null);</pre> </p> <p> The repository's <code>Read</code> method returns <code>Maybe&lt;Reservation&gt;</code>, indicating that it's possible that no object is returned. This will happen if you're querying the repository for an <code>id</code> that doesn't exist in the underlying database. </p> <p> While you can translate the (potential) <code>Reservation</code> object to a view model (using the <code>ToViewModel</code> extension method), you'll have to supply a default view model to handle the case when the reservation wasn't found. </p> <p> <code>ReservationViewModel.Null</code> is a static read-only class field implementing the <a href="https://en.wikipedia.org/wiki/Null_Object_pattern">Null Object pattern</a>. Here, it's used for the fall-back value, in case no object was returned from the repository. </p> <p> Notice that while you need a fall-back value at the end of your <a href="https://martinfowler.com/bliki/FluentInterface.html">fluent interface</a> pipeline, you don't need fall-back values for any intermediate steps. Specifically, you don't need a Null Object implementation for your domain model (<code>Reservation</code>). Furthermore, no defensive coding is required, because <code>Maybe&lt;T&gt;</code> guarantees that the object passed to <code>selector</code> is never <code>null</code>. </p> <h3 id="e5b5aead20eb4f62947a5e0b100b1beb"> First functor law <a href="#e5b5aead20eb4f62947a5e0b100b1beb" title="permalink">#</a> </h3> <p> A <code>Select</code> method with the right signature isn't enough to be a functor. It must also obey the functor laws. Maybe obeys both laws, which you can demonstrate with a few examples. Here's some test cases for a populated Maybe: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foo&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;bar&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;corge&quot;</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;antidisestablishmentarianism&quot;</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;PopulatedMaybeObeysFirstFunctorLaw(<span style="color:blue;">string</span>&nbsp;value) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;id&nbsp;=&nbsp;x&nbsp;=&gt;&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;m&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">string</span>&gt;(value); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(m,&nbsp;m.Select(id)); }</pre> </p> <p> This parametrised unit test uses <a href="https://xunit.github.io">xUnit.net</a> to demonstrate that a populated Maybe value doesn't change when translated with the local <code>id</code> function, since <code>id</code> returns the input unchanged. </p> <p> The first functor law holds for an empty Maybe as well: </p> <p> <pre>[<span style="color:#2b91af;">Fact</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;EmptyMaybeObeysFirstFunctorLaw() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;id&nbsp;=&nbsp;x&nbsp;=&gt;&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;m&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">string</span>&gt;(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(m,&nbsp;m.Select(id)); }</pre> </p> <p> When a Maybe starts empty, translating it with <code>id</code> doesn't change that it's empty. It's worth noting, however, that the original and the translated objects are considered equal because <code>Maybe&lt;T&gt;</code> overrides <code>Equals</code>. Even in the case of the empty Maybe, the value returned by <code>Select(id)</code> is a new object, with a memory address different from the original value. </p> <h3 id="1f17f61c26f9481aa3eea8d033ed3afc"> Second functor law <a href="#1f17f61c26f9481aa3eea8d033ed3afc" title="permalink">#</a> </h3> <p> You can also demonstrate the second functor law with some examples, starting with some test cases for the populated case: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;&quot;</span>,&nbsp;<span style="color:blue;">true</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;<span style="color:blue;">false</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;bar&quot;</span>,&nbsp;<span style="color:blue;">false</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;corge&quot;</span>,&nbsp;<span style="color:blue;">false</span>)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;antidisestablishmentarianism&quot;</span>,&nbsp;<span style="color:blue;">true</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;PopulatedMaybeObeysSecondFunctorLaw(<span style="color:blue;">string</span>&nbsp;value,&nbsp;<span style="color:blue;">bool</span>&nbsp;expected) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;g&nbsp;=&nbsp;s&nbsp;=&gt;&nbsp;s.Length; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">bool</span>&gt;&nbsp;&nbsp;&nbsp;f&nbsp;=&nbsp;i&nbsp;=&gt;&nbsp;i&nbsp;%&nbsp;2&nbsp;==&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;m&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">string</span>&gt;(value); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(m.Select(g).Select(f),&nbsp;m.Select(s&nbsp;=&gt;&nbsp;f(g(s)))); }</pre> </p> <p> In this parametrised test, <code>f</code> and <code>g</code> are two local functions. <code>g</code> returns the length of a string (for example, the length of <em>antidisestablishmentarianism</em> is <em>28</em>). <code>f</code> evaluates whether or not a number is even. </p> <p> Whether you decide to first translate <code>m</code> with <code>g</code>, and then translate the return value with <code>f</code>, or you decide to translate the composition of those functions in a single <code>Select</code> method call, the result should be the same. </p> <p> The second functor law holds for the empty case as well: </p> <p> <pre>[<span style="color:#2b91af;">Fact</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;EmptyMaybeObeysSecondFunctorLaw() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;g&nbsp;=&nbsp;s&nbsp;=&gt;&nbsp;s.Length; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">bool</span>&gt;&nbsp;&nbsp;&nbsp;f&nbsp;=&nbsp;i&nbsp;=&gt;&nbsp;i&nbsp;%&nbsp;2&nbsp;==&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;m&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">string</span>&gt;(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(m.Select(g).Select(f),&nbsp;m.Select(s&nbsp;=&gt;&nbsp;f(g(s)))); }</pre> </p> <p> Since <code>m</code> is empty, applying the translations doesn't change that fact - it only changes the type of the resulting object, which is an empty <code>Maybe&lt;bool&gt;</code>. </p> <h3 id="9468d48e71ea45c8b17540919be78b0f"> Haskell <a href="#9468d48e71ea45c8b17540919be78b0f" title="permalink">#</a> </h3> <p> In <a href="https://www.haskell.org">Haskell</a>, Maybe is built in. You can create a <code>Maybe</code> value containing an integer like this (the type annotations are optional): </p> <p> <pre><span style="color:#600277;">source</span>&nbsp;::&nbsp;Maybe&nbsp;Int source&nbsp;<span style="color:#666666;">=</span>&nbsp;Just&nbsp;<span style="color:#09885a;">42</span></pre> </pre> </p> <p> Mapping <code>source</code> to a <code>String</code> can be done like this: </p> <p> <pre><span style="color:#600277;">dest</span>&nbsp;::&nbsp;Maybe&nbsp;String dest&nbsp;<span style="color:#666666;">=</span>&nbsp;fmap&nbsp;show&nbsp;source</pre> </p> <p> The function <code>fmap</code> corresponds to the above C# <code>Select</code> method. </p> <p> It's also possible to use infix notation: </p> <p> <pre><span style="color:#600277;">dest</span>&nbsp;::&nbsp;Maybe&nbsp;String dest&nbsp;<span style="color:#666666;">=</span>&nbsp;show&nbsp;<span style="color:#666666;">&lt;$&gt;</span>&nbsp;source</pre> </p> <p> The <code>&lt;$&gt;</code> operator is an alias for <code>fmap</code>. </p> <p> Whether you use <code>fmap</code> or <code>&lt;$&gt;</code>, the resulting <code>dest</code> value is <code>Just "42"</code>. </p> <p> If you want to create an empty <code>Maybe</code> value, you use the <code>Nothing</code> data constructor. </p> <h3 id="76073b1acf7f4b9ab72f873738dec4f4"> F# <a href="#76073b1acf7f4b9ab72f873738dec4f4" title="permalink">#</a> </h3> <p> Maybe is also a built-in type in F#, but here it's called <code>option</code> instead of <code>Maybe</code>. You create an option containing an integer like this: </p> <p> <pre><span style="color:green;">//&nbsp;int&nbsp;option</span> <span style="color:blue;">let</span>&nbsp;source&nbsp;=&nbsp;<span style="color:navy;">Some</span>&nbsp;42</pre> </p> <p> While the case where a value is present was denoted with <code>Just</code> in Haskell, in F# it's called <code>Some</code>. </p> <p> You can translate option values using the <code>map</code> function from the <code>Option</code> module: </p> <p> <pre><span style="color:green;">//&nbsp;string&nbsp;option</span> <span style="color:blue;">let</span>&nbsp;dest&nbsp;=&nbsp;source&nbsp;|&gt;&nbsp;<span style="color:teal;">Option</span>.<span style="color:navy;">map</span>&nbsp;<span style="color:navy;">string</span></pre> </p> <p> Finally, if you want to create an empty <code>option</code> value, you can use the <code>None</code> case constructor. </p> <h3 id="5c14e63d3b50485f8252718eae911d04"> Summary <a href="#5c14e63d3b50485f8252718eae911d04" title="permalink">#</a> </h3> <p> Together with a functor called <em>Either</em>, Maybe is one of the workhorses of statically typed functional programming. You aren't going to write much F# or Haskell before you run into it. In C# I've used variations of the above <code>Maybe&lt;T&gt;</code> class for years, with much success. </p> <p> In this article, I only discussed Maybe in its role of being a functor, but it's so much more than that! It's also an applicative functor, a monad, and traversable (enumerable). Not all functors are that rich. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/08/06/a-tree-functor">A Tree functor</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Functors http://blog.ploeh.dk/2018/03/22/functors 2018-03-22T16:57:00+00:00 Mark Seemann <div id="post"> <p> <em>A functor is a common abstraction. While typically associated with functional programming, functors exist in C# as well.</em> </p> <p> This article series is part of <a href="http://blog.ploeh.dk/2018/03/19/functors-applicatives-and-friends">a larger series of articles about functors, applicatives, and other mappable containers</a>. </p> <p> Programming is about abstraction, since you can't manipulate individual sub-atomic particles on your circuit boards. Some abstractions are well-known because they're rooted in mathematics. Particularly, <a href="https://en.wikipedia.org/wiki/Category_theory">category theory</a> has proven to be fertile ground for functional programming. Some of the concepts from category theory apply to object-oriented programming as well; all you need is generics, which is a feature of both C# and Java. </p> <p> In previous articles, you got an introduction to the specific <a href="http://blog.ploeh.dk/2017/08/14/from-test-data-builders-to-the-identity-functor">Test Data Builder</a> and <a href="http://blog.ploeh.dk/2017/09/18/the-test-data-generator-functor">Test Data Generator</a> functors. Functors are more common than you may realise, although in programming, we usually work with a subset of functors called <em>endofunctors</em>. In daily speak, however, we just call them <em>functors</em>. </p> <p> In the next series of articles, you'll see plenty of examples of functors, with code examples in both C#, F#, and Haskell. These articles are mostly aimed at object-oriented programmers curious about the concept. <ul> <li><a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">The Maybe functor</a></li> <li><a href="http://blog.ploeh.dk/2018/08/06/a-tree-functor">A Tree functor</a></li> <li><a href="http://blog.ploeh.dk/2018/08/13/a-visitor-functor">A Visitor functor</a></li> <li><a href="http://blog.ploeh.dk/2018/08/20/reactive-functor">Reactive functor</a></li> <li><a href="http://blog.ploeh.dk/2018/09/03/the-identity-functor">The Identity functor</a></li> <li><a href="http://blog.ploeh.dk/2018/09/10/the-lazy-functor">The Lazy functor</a></li> <li>Asynchronous functors</li> </ul> This list is far from exhaustive; more functors exist. Perhaps the most well-known of all functors is List, a.k.a. Sequence. C# query syntax can handle any functor, but most people only think of it as a language feature related to <code>IEnumerable&lt;T&gt;</code>. Since the combination of <code>IEnumerable&lt;T&gt;</code> and query syntax is already well-described, I'm not going to cover it explicitly here. </p> <p> If you understand how LINQ, <code>IEnumerable&lt;T&gt;</code>, and C# query syntax works, however, all other functors should feel intuitive. That's the power of abstractions. </p> <h3 id="3053c67ef9dd4d21bd68ccc1ddbd208a"> Overview <a href="#3053c67ef9dd4d21bd68ccc1ddbd208a" title="permalink">#</a> </h3> <p> The purpose of this article isn't to give you a comprehensive introduction to the category theory of functors. Rather, the purpose is to give you an opportunity to learn how it translates to object-oriented code like C#. For a great introduction to functors, see <a href="https://bartoszmilewski.com">Bartosz Milewski</a>'s <a href="https://bartoszmilewski.com/2015/01/20/functors">explanation with illustrations</a>. </p> <p> In short, a functor is a mapping between two categories. A functor maps not only objects, but also functions (called <em>morphisms</em>) between objects. For instance, a functor <em>F</em> may be a mapping between the categories <em>C</em> and <em>D</em>: </p> <p> <img src="/content/binary/functor-diagram.png" alt="Functor diagram."> </p> <p> Not only does <em>F</em> map <em>a</em> from <em>C</em> to <em>F a</em> in <em>D</em> (and likewise for <em>b</em>), it also maps the function <em>f</em> to <em>F f</em>. Functors preserve the structure between objects. You'll often hear the phrase that a functor is a <em>structure-preserving map</em>. One example of this regards lists. You can translate a <code>List&lt;int&gt;</code> to a <code>List&lt;string&gt;</code>, but the translation preserves the structure. This means that the resulting object is also a list, and the order of values within the lists doesn't change. </p> <p> In category theory, categories are often named <em>C</em>, <em>D</em>, and so on, but an example of a category could be <code>IEnumerable&lt;T&gt;</code>. If you have a function that translates integers to strings, the source <em>object</em> (that's what it's called, but it's not the same as an OOP object) could be <code>IEnumerable&lt;int&gt;</code>, and the destination object could be <code>IEnumerable&lt;string&gt;</code>. A functor, then, represents the ability to go from <code>IEnumerable&lt;int&gt;</code> to <code>IEnumerable&lt;string&gt;</code>, and since the <a href="https://msdn.microsoft.com/en-us/library/bb548891">Select</a> method gives you that ability, <code>IEnumerable&lt;T&gt;.Select</code> is a functor. In this case, you sort of 'stay within' the category of <code>IEnumerable&lt;T&gt;</code>, only you change the generic type argument, so this functor is really an endofunctor (the <em>endo</em> prefix is from Greek, meaning <em>within</em>). </p> <p> As a rule of thumb, if you have a type with a generic type argument, it's a candidate to be a functor. Such a type is not always a functor, because it also depends on where the generic type argument appears, and some other rules. </p> <p> Fundamentally, you must be able to implement a method for your generic type that looks like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Functor</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;Select&lt;<span style="color:#2b91af;">TResult</span>&gt;(<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;selector) </pre> </p> <p> Here, I've defined the <code>Select</code> method as an instance method on a class called <code>Functor&lt;T&gt;</code>, but often, as is the case with <code>IEnumerable&lt;T&gt;</code>, the method is instead implemented as an extension method. You don't have to name it <code>Select</code>, but doing so enables query syntax in C#: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;dest&nbsp;=&nbsp;<span style="color:blue;">from</span>&nbsp;x&nbsp;<span style="color:blue;">in</span>&nbsp;source &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;x.ToString();</pre> </p> <p> Here, <code>source</code> is a <code>Functor&lt;int&gt;</code> object. </p> <p> If you don't name the method <code>Select</code>, it could still be a functor, but then query syntax wouldn't work. Instead, normal method-call syntax would be your only option. This is, however, a specific C# language feature. F#, for example, has no particular built-in awareness of functors, although most libraries name the central function <code>map</code>. In Haskell, <code>Functor</code> is a typeclass that defines a function called <code>fmap</code>. </p> <p> The common trait is that there's an input value (<code>Functor&lt;T&gt;</code> in the above C# code snippet), which, when combined with a mapping function (<code>Func&lt;T, TResult&gt;</code>), returns an output value of the same generic type, but with a different generic type argument (<code>Functor&lt;TResult&gt;</code>). </p> <h3 id="314a59e80ab4476381e0ed3205d35491"> Laws <a href="#314a59e80ab4476381e0ed3205d35491" title="permalink">#</a> </h3> <p> Defining a <code>Select</code> method isn't enough. The method must also obey the so-called <em>functor laws</em>. These are quite intuitive laws that govern that a functor behaves correctly. </p> <p> The first law is that mapping the identity function returns the functor unchanged. The <em>identity function</em> is a function that returns all input unchanged. (It's called the <em>identity function</em> because it's the <em>identity</em> for the <a href="http://blog.ploeh.dk/2017/11/13/endomorphism-monoid">endomorphism monoid</a>.) In F# and Haskell, this is simply a built-in function called <code>id</code>. </p> <p> In C#, you can write a demonstration of the law as a unit test: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(-101)] [<span style="color:#2b91af;">InlineData</span>(-1)] [<span style="color:#2b91af;">InlineData</span>(0)] [<span style="color:#2b91af;">InlineData</span>(1)] [<span style="color:#2b91af;">InlineData</span>(42)] [<span style="color:#2b91af;">InlineData</span>(1337)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;FunctorObeysFirstFunctorLaw(<span style="color:blue;">int</span>&nbsp;value) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;id&nbsp;=&nbsp;x&nbsp;=&gt;&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;sut&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Functor</span>&lt;<span style="color:blue;">int</span>&gt;(value); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(sut,&nbsp;sut.Select(id)); }</pre> </p> <p> While this doesn't <em>prove</em> that the first law holds for all values and all generic type arguments, it illustrates what's going on. </p> <p> Since C# doesn't have a built-in identity function, the test creates a specialised identity function for integers, and calls it <code>id</code>. It simply returns all input values unchanged. Since <code>id</code> doesn't change the value, then <code>Select(id)</code> shouldn't change the functor, either. There's nothing more to the first law than this. </p> <p> The second law states that if you have two functions, <code>f</code> and <code>g</code>, then mapping over one after the other should be the same as mapping over the composition of <code>f</code> and <code>g</code>. In C#, you can illustrate it like this: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(-101)] [<span style="color:#2b91af;">InlineData</span>(-1)] [<span style="color:#2b91af;">InlineData</span>(0)] [<span style="color:#2b91af;">InlineData</span>(1)] [<span style="color:#2b91af;">InlineData</span>(42)] [<span style="color:#2b91af;">InlineData</span>(1337)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;FunctorObeysSecondFunctorLaw(<span style="color:blue;">int</span>&nbsp;value) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;&nbsp;&nbsp;&nbsp;g&nbsp;=&nbsp;i&nbsp;=&gt;&nbsp;i.ToString(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;f&nbsp;=&nbsp;s&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:blue;">string</span>(s.Reverse().ToArray()); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;sut&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Functor</span>&lt;<span style="color:blue;">int</span>&gt;(value); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(sut.Select(g).Select(f),&nbsp;sut.Select(i&nbsp;=&gt;&nbsp;f(g(i)))); }</pre> </p> <p> Here, <code>g</code> is a function that translates an <code>int</code> to a <code>string</code>, and <code>f</code> reverses a string. Since <code>g</code> returns <code>string</code>, you can compose it with <code>f</code>, which takes <code>string</code> as input. </p> <p> As the assertion points out, it shouldn't matter if you call <code>Select</code> piecemeal, first with <code>g</code> and then with <code>f</code>, or if you call <code>Select</code> with the composed function <code>f(g(i))</code>. </p> <h3 id="eb061f6fdd094731a1c52850eec7feac"> Summary <a href="#eb061f6fdd094731a1c52850eec7feac" title="permalink">#</a> </h3> <p> This is not a monad tutorial; it's a functor tutorial. Functors are commonplace, so it's worth keeping an eye out for them. If you already understand how LINQ (or similar concepts in Java) work, then functors should be intuitive, because they are all based on the same underlying maths. </p> <p> While this article is an overview article, it's also a part of <a href="http://blog.ploeh.dk/2017/10/04/from-design-patterns-to-category-theory">a larger series of articles</a> that explore what object-oriented programmers can learn from category theory. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">The Maybe functor</a>. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="419959edeb1c45b785bb732a83c5134d"> <div class="comment-author"><a href="https://twitter.com/philip_schwarz">Philip Schwarz</a></div> <div class="comment-content">For anyone interested in an aid to internalising functor laws, check out the first four diagrams of the following slide deck, which summarise the laws (in category-theoretic terms) and show an example of the laws in action for a functor from one monoid to another: <a href="https://www.slideshare.net/pjschwarz/functor-laws">Functor Laws</a><br></div> <div class="comment-date">2018-08-18 11:00 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Functors, applicatives, and friends http://blog.ploeh.dk/2018/03/19/functors-applicatives-and-friends 2018-03-19T08:35:00+00:00 Mark Seemann <div id="post"> <p> <em>Functors and related data structures are containers of values. It's a family of abstractions. An overview for object-oriented programmers.</em> </p> <p> This article series is part of <a href="http://blog.ploeh.dk/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> </p> <p> If you've worked with C# or Java recently, you've most likely encountered types such as <code>Foo&lt;T&gt;</code> or <code>Bar&lt;T&gt;</code> (specifically, on .NET, e.g. <a href="https://msdn.microsoft.com/en-us/library/6sh2ey19">List&lt;T&gt;</a>). Perhaps you've also noticed that often, you can translate the type inside of <a href="https://bartoszmilewski.com/2014/01/14/functors-are-containers">the container</a>. For example, if you have a <code>Foo&lt;string&gt;</code>, perhaps you can call some method on it that returns a <code>Foo&lt;int&gt;</code>. If so, it may be a <em>functor</em>. </p> <p> Not all generic types are functors. In order to be a functor, a generic type must obey a couple of intuitive laws. You'll learn about those in future articles. </p> <p> Some functors have extra capabilities, and you'll learn about some of those as well. Some are called <em>applicative functors</em>, and some are called <em>bifunctors</em>. There are others, as well. </p> <p> <img src="/content/binary/functors-applicatives-bifunctors.png" alt="Functors, applicative functors, and bifunctors as subsets of each other."> </p> <p> All applicative functors are functors, and this is true for bifunctors as well. </p> <p> In this article series, you'll learn about the following categories: <ul> <li><a href="http://blog.ploeh.dk/2018/03/22/functors">Functors</a> <ul> <li><a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">The Maybe functor</a></li> <li><a href="http://blog.ploeh.dk/2018/08/06/a-tree-functor">A Tree functor</a></li> <li><a href="http://blog.ploeh.dk/2018/08/13/a-visitor-functor">A Visitor functor</a></li> <li><a href="http://blog.ploeh.dk/2018/08/20/reactive-functor">Reactive functor</a></li> <li><a href="http://blog.ploeh.dk/2018/09/03/the-identity-functor">The Identity functor</a></li> <li><a href="http://blog.ploeh.dk/2018/09/10/the-lazy-functor">The Lazy functor</a></li> <li>Asynchronous functors</li> </ul> </li> <li>Applicative functors <ul> <li>Deck of cards</li> <li>Guess a password</li> <li>Applicative sequences as combinations</li> <li>Maybe</li> <li>Validation</li> <li>Test Data Generator</li> <li>Danish CPR numbers in F#</li> </ul> </li> <li>Bifunctors <ul> <li>Tuple bifunctor</li> <li>Either bifunctor</li> </ul> </li> </ul> You'll see plenty of examples along the way. Most examples will be in C#, but some articles will have code examples in <a href="http://fsharp.org">F#</a> or <a href="https://www.haskell.org">Haskell</a>. You can read or skip those articles as you prefer. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/03/22/functors">Functors</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Composite as a monoid http://blog.ploeh.dk/2018/03/12/composite-as-a-monoid 2018-03-12T09:39:00+00:00 Mark Seemann <div id="post"> <p> <em>When can you use the Composite design pattern? When the return types of your methods form monoids.</em> </p> <p> This article is part of <a href="http://blog.ploeh.dk/2018/03/05/some-design-patterns-as-universal-abstractions/">a series of articles about design patterns and their universal abstraction counterparts</a>. </p> <p> The <a href="https://en.wikipedia.org/wiki/Composite_pattern">Composite</a> design pattern is a powerful way to structure code, but not all objects are composable. When is an object composable? This article explores that question. </p> <p> In short, Composites are <a href="http://blog.ploeh.dk/2017/10/06/monoids">monoids</a>. </p> <p> <img src="/content/binary/composite-as-subset-of-monoid.png" alt="Composite shown as a subset of the set of monoids."> </p> <p> Not all monoids are Composites, but as far as I can tell, all Composites are monoids. </p> <h3 id="ab8f3501700042419375b91315249a77"> Composite <a href="#ab8f3501700042419375b91315249a77" title="permalink">#</a> </h3> <p> First, I'll use various <a href="http://blog.ploeh.dk/2018/01/08/software-design-isomorphisms">software design isomorphisms</a> to put Composite in a canonical form. From <a href="http://blog.ploeh.dk/2018/01/15/unit-isomorphisms">unit isomorphisms</a>, <a href="http://blog.ploeh.dk/2018/01/22/function-isomorphisms">function isomorphisms</a>, and <a href="http://blog.ploeh.dk/2018/01/29/argument-list-isomorphisms">argument list isomorphisms</a>, we know that we can represent any method as a method or function that takes a single argument, and returns a single output value. From <a href="http://blog.ploeh.dk/2018/02/19/abstract-class-isomorphism">abstract class isomorphism</a> we know that we can represent an abstract class with interfaces. Thus, you can represent the interface for a Composite like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IInterface1</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Out1</span>&nbsp;Op1(<span style="color:#2b91af;">In1</span>&nbsp;arg); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Out2</span>&nbsp;Op2(<span style="color:#2b91af;">In2</span>&nbsp;arg); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Out3</span>&nbsp;Op3(<span style="color:#2b91af;">In3</span>&nbsp;arg); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;More&nbsp;operations...</span> }</pre> </p> <p> In order to create a Composite, we must be able to take an arbitrary number of implementations and make them look like a single object. </p> <h3 id="30b860e1b0904901a41b1ead2424a74d"> Composite as monoid <a href="#30b860e1b0904901a41b1ead2424a74d" title="permalink">#</a> </h3> <p> You have a set of implementations of <code>IInterface1</code>. In order to create a Composite, you loop over all of those implementations in order to produce an aggregated result. Imagine that you have to implement a <code>CompositeInterface1</code> class that composes <code>imps</code>, an <code>IReadOnlyCollection&lt;IInterface1&gt;</code>. In order to implement <code>Op1</code>, you'd have to write code like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Out1</span>&nbsp;Op1(<span style="color:#2b91af;">In1</span>&nbsp;arg) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">foreach</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;imp&nbsp;<span style="color:blue;">in</span>&nbsp;<span style="color:blue;">this</span>.imps) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;out1&nbsp;=&nbsp;imp.Op1(arg); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;Somehow&nbsp;combine&nbsp;this&nbsp;out1&nbsp;value&nbsp;with&nbsp;previous&nbsp;values</span> &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;Return&nbsp;combined&nbsp;Out1&nbsp;value</span> }</pre> </p> <p> This implies that we have an ordered, finite sequence of implementations: <em>imp1, imp2, imp3, ...</em>. In C#, we could represent such a sequence with the type <code>IReadOnlyCollection&lt;IInterface1&gt;</code>. Somehow, we need to turn that collection into a single <code>IInterface1</code> value. In other words, we need a translation of the type <code>IReadOnlyCollection&lt;IInterface1&gt; -&gt; IInterface1</code>. </p> <p> If we look to <a href="https://www.haskell.org">Haskell</a> for inspiration for a moment, let's replace <code>IReadOnlyCollection&lt;T&gt;</code> with Haskell's built-in linked list. This means that we need a function of the type <code>[IInterface1] -&gt; IInterface1</code>, or, more generally, <code>[a] -&gt; a</code>. This function exists for all <code>a</code> as long as <code>a</code> forms a monoid; it's called <code>mconcat</code>: </p> <p> <pre>mconcat :: Monoid a =&gt; [a] -&gt; a</pre> </p> <p> We also know from a previous article that <a href="http://blog.ploeh.dk/2017/11/20/monoids-accumulate">a collection of monoids can be reduced to a single monoid</a>. Notice how the above outline of a composite implementation of <code>Op1</code> looks similar to the <code>Accumulate</code> method shown in the linked article. If <code>IInterface1</code> can form a monoid, then you can make a Composite. </p> <h3 id="79bbc5e304734bb180724a77929e23b6"> Objects as monoids <a href="#79bbc5e304734bb180724a77929e23b6" title="permalink">#</a> </h3> <p> When can an object (like <code>IInterface1</code>) form a monoid? </p> <p> From <a href="http://blog.ploeh.dk/2018/02/12/object-isomorphisms">object isomorphisms</a> we know that we can decompose an object with <em>n</em> members to <em>n</em> static methods. This means that instead of analysing all of <code>IInterface1</code>, we can consider the properties of each method in isolation. The properties of an object is the consolidation of the properties of all the methods. </p> <p> Recall, still from <em>object isomorphisms</em>, that we can represent an object as a tuple of functions. Moreover, <a href="http://blog.ploeh.dk/2017/10/30/tuple-monoids">if you have a tuple of monoids, then the tuple also forms monoid</a>! </p> <p> In order to make an object a monoid, then, you have to make each method a monoid. When is a method a monoid? <a href="http://blog.ploeh.dk/2017/11/06/function-monoids">A method is a monoid when its return type forms a monoid</a>. </p> <p> That's it. An interface like <code>IInterface1</code> is a monoid when <code>Out1</code>, <code>Out2</code>, <code>Out3</code>, and so on, form monoids. If that's the case, you can make a Composite. </p> <h3 id="75ca550ef1ef42b3a559bece1ff6b52d"> Examples <a href="#75ca550ef1ef42b3a559bece1ff6b52d" title="permalink">#</a> </h3> <p> From <em>unit isomorphism</em>, we know that we can represent C#'s and Java's <em>void</em> keywords with methods returning <em>unit</em>, and <em>unit</em> is a monoid. All methods that return <code>void</code> can be part of a Composite, but we already knew that <a href="http://blog.ploeh.dk/2011/03/22/CommandsareComposable">Commands are composable</a>. If you search for examples of the Composite design pattern, you'll find more than one variation involving drawing shapes on a digital canvas, with the central operation being a <code>Draw</code> method with a <code>void</code> return type. </p> <p> Another example could be calculation of the price of a shopping basket. If you have an interface method of the type <code>decimal Calculate(Basket basket)</code>, you could have several implementations: <ul> <li>Add all the item prices together</li> <li>Apply a discount (a negative number)</li> <li>Calculate sales tax</li> </ul> These could be three implementations of the same interface method, and since decimal numbers form a monoid over addition, then you can make a Composite basket calculator out of the three implementations. For a detailed example, see the <a href="http://blog.ploeh.dk/2018/05/17/composite-as-a-monoid-a-business-rules-example">coda containing a business rules example</a>. </p> <p> Boolean values also form at least two monoids (<em>any</em> and <em>all</em>), so any method you have that returns a Boolean value can be used in a Composite. You could, for example, have a list of criteria for granting a loan. Each such business rule returns <code>true</code> if it evaluates that the loan should be granted, and <code>false</code> otherwise. If you have more than one business rule, you can create a Composite that returns <code>true</code> only if all the individual rules return <code>true</code>. </p> <p> If you have a method that returns a string, then that is also a candidate for inclusion in a Composite, if string concatenation makes sense in the domain in question. </p> <p> You probably find it fairly mundane that you can create a Composite if all the methods involved return numbers, strings, Booleans, or nothing. The result generalises, however, to all monoids, including more complex types, including methods that return other interfaces that themselves form monoids, and so on recursively. </p> <h3 id="3d21d64a1ec64432abd38ebcd09332a6"> Granularity <a href="#3d21d64a1ec64432abd38ebcd09332a6" title="permalink">#</a> </h3> <p> The result, then, is that you can make a Composite when <em>all</em> methods in your interface have monoidal return types. If only a single method has a return type that isn't a monoid, you can't aggregate that value, and you can't make a Composite. </p> <p> Your interface can have as many methods you like, but they must all be monoids. Even one rogue method will prevent you from being able to create a Composite. This is another argument for <a href="https://martinfowler.com/bliki/RoleInterface.html">Role Interfaces</a>. The smaller an interface is, the more likely it is that you can make a Composite out of it. If you follow that line of reasoning to its ultimate conclusion, you'll <a href="http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional">design your interfaces with a single member each</a>. </p> <h3 id="f98c1cf3efa24c919cc10fba5d672435"> Relaxation <a href="#f98c1cf3efa24c919cc10fba5d672435" title="permalink">#</a> </h3> <p> There can be some exceptions to the rule that all return values must be monoids. If you have at least one implementation of your interface, then a <a href="http://blog.ploeh.dk/2017/11/27/semigroups">semigroup</a> may be enough. Recall that monoids accumulate like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Foo</span>&nbsp;Accumulate(<span style="color:#2b91af;">IReadOnlyCollection</span>&lt;<span style="color:#2b91af;">Foo</span>&gt;&nbsp;foos) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;acc&nbsp;=&nbsp;Identity; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">foreach</span>&nbsp;(<span style="color:blue;">var</span>&nbsp;f&nbsp;<span style="color:blue;">in</span>&nbsp;foos) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;acc&nbsp;=&nbsp;acc.Op(f); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;acc; }</pre> </p> <p> You only need <code>Identity</code> in order to start the accumulation, and to have something to return in case you have no implementations. If you have at least one implementation, you don't need the identity, and then <a href="http://blog.ploeh.dk/2017/12/11/semigroups-accumulate">a semigroup is enough to accumulate</a>. Consider the <a href="http://blog.ploeh.dk/2017/12/04/bounding-box-semigroup">bounding box example</a>. If you have a method that returns <code>BoundingBox</code> values, you can still make a Composite out of such an interface, as long as you have at least one implementation. There's no 'identity' bounding box, but it makes intuitive sense that you can still compose bounding boxes into bigger bounding boxes. </p> <p> Haskell formalises the rule for semigroups: </p> <p> <pre>sconcat :: Semigroup a =&gt; Data.List.NonEmpty.NonEmpty a -&gt; a</pre> </p> <p> The <code>sconcat</code> function reduces any non-empty list of any semigroup <code>a</code> to a single <code>a</code> value. </p> <p> If you have a non-empty list of implementations, then perhaps you don't even need a semigroup. Perhaps any <a href="http://blog.ploeh.dk/2017/12/27/magmas">magma</a> will work. Be aware, however, that the lack of associativity will cause the order of implementations to matter. </p> <p> Technically, you may be able to program a Composite from a magma, but I'd suggest caution. The monoid and semigroup laws are intuitive. A magma without those properties may not form an intuitive Composite. While it may compile, it may have surprising, or counter-intuitive, behaviour. I'd favour sticking to monoids or semigroups. </p> <h3 id="b30a2eafacfb4ddf98caec0c2030bf49"> Summary <a href="#b30a2eafacfb4ddf98caec0c2030bf49" title="permalink">#</a> </h3> <p> When is an object-oriented design composable? Composition could mean more than one thing, but this article has focused exclusively on the Composite design pattern. When can you use the Composite pattern? When all method return types are monoids. </p> <p> <strong>Next: </strong> <a href="http://blog.ploeh.dk/2018/04/09/coalescing-composite-as-a-monoid">Coalescing Composite as a monoid</a>. </p> </div><hr> This blog is totally free, but if you like it, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZEPYW8KVZ8WL">buy me a cup of coffee</a>. Some design patterns as universal abstractions http://blog.ploeh.dk/2018/03/05/some-design-patterns-as-universal-abstractions 2018-03-05T08:10:00+00:00 Mark Seemann <div id="post"> <p> <em>Some design patterns can be formalised by fundamental abstractions.</em> </p> <p> This article series submits results based on the work presented in <a href="http://blog.ploeh.dk/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>. </p> <p> Wouldn't it be wonderful if you could assemble software from predefined building blocks? This idea is <em>old</em>, and has been the driving force behind object-oriented programming (OOP). In <a href="https://www.coupland.com">Douglas Coupland</a>'s 1995 novel <a href="http://bit.ly/microserfs">Microserfs</a>, the characters attempt to reach that goal through a project called <em>Oop!</em>. <a href="https://en.wikipedia.org/wiki/Lego">Lego bricks</a> play a role as a metaphor as well. </p> <p> <img src="/content/binary/lego-bricks-as-connections.png" alt="Lego bricks."> </p> <p> Decades later, it doesn't look like we're much nearer that goal than before, but I believe that we'd made at least two (rectifiable) mistakes along the way: <ul> <li>Granularity</li> <li>Object-orientation</li> </ul> While I'm going to discuss both of these briefly, my principal message is one of hope. I still think we can assemble software from predefined 'things', but I believe that these 'things' are small and 'objects' in a different sense than normal. </p> <h3 id="e1bedfebfd5d4292a18a5a2eecf763c9"> Granularity <a href="#e1bedfebfd5d4292a18a5a2eecf763c9" title="permalink">#</a> </h3> <p> Over the years, I've seen several attempts at reducing software development to a matter of putting things together. These attempts have invariably failed. </p> <p> I believe that one of the reasons for failure is that such projects tend to aim at coarse-grained building blocks. As I explain in the <em>Interface Segregation Principle</em> module of my <a href="http://blog.ploeh.dk/encapsulation-and-solid">Encapsulation and SOLID</a> Pluralsight course, granularity is a crucial determinant for your ability to create. The coarser-grained the building blocks, the harder it is to create something useful. </p> <p> Most attempts at software-as-building-blocks have used big, specialised building blocks aimed at non-technical users (<em>"Look! Create an entire web site without writing a single line of code!"</em>). That's just like <a href="https://en.wikipedia.org/wiki/Lego_Duplo">Duplo</a>. You can create exactly what the blocks were designed for, but as soon as you try to create something new and original, you can't. </p> <h3 id="11a18062d294481bb092e2d4c364b4a4"> Object-orientation <a href="#11a18062d294481bb092e2d4c364b4a4" title="permalink">#</a> </h3> <p> OOP is another attempt at software-as-building-blocks. In .NET (the OOP framework with which I'm most familiar) the Base Class Library (BCL) is enormous. Many of the reusable objects in the BCL are fine-grained, so at least it's often possible to put them together to create something useful. The problem with an object-oriented library like the .NET BCL, however, is that all the objects are <em>special</em>. </p> <p> The vision was always that software 'components' would be able to 'click' together, just like Lego bricks. The BCL isn't like that. Typically, objects have nothing in common apart from the useless <code>System.Object</code> base class. There's no system. In order to learn how the BCL works, you have to learn the ins and outs of every single class. </p> <p> Better know a framework. </p> <p> It doesn't help that OOP was never formally defined. Every time you see or hear a discussion about what 'real' object-orientation is, you can be sure that sooner or later, someone will say: "...but that's not what <a href="https://en.wikipedia.org/wiki/Alan_Kay">Alan Kay</a> had in mind." </p> <p> What Alan Kay had in mind is still unclear to me, but it seems safe to say that it wasn't what we have now (C++, Java, C#). </p> <h3 id="5