ploeh blog 2018-11-15T07:19:15+00:00 Mark Seemann danish software design http://blog.ploeh.dk What to test and not to test http://blog.ploeh.dk/2018/11/12/what-to-test-and-not-to-test 2018-11-12T07:45:00+00:00 Mark Seemann <div id="post"> <p> <em>Should you unit test everything? Hardly surprising, the answer is that It Depends™. This article outlines some of the circumstances you might consider.</em> </p> <p> Some years ago, I, somewhat to my own surprise, found myself on the wrong side of a controversy about whether one should <a href="http://blog.ploeh.dk/2013/03/08/test-trivial-code">test trivial code</a>. The context was a discussion about Test-Driven Development (TDD), and for reasons that I still stand behind today, I argued that you should test all code, including trivial code, such as property getters. </p> <p> Most of the 'TDD community' reacted quite negatively to that article, some in not-so-nice ways. Some people reacted, I believe, based on their dislike of the conclusion, without responding to my arguments. Others, however, gave reasoned rebuttals. When people like <a href="https://lostechies.com/derickbailey/2013/03/11/on-testing-trivia-code/">Derick Bailey</a> and <a href="https://rendlelabs.com/blog/dont-unit-test-trivial-code">Mark Rendle disagree with me</a>, in a reasoned matter, even, I consider that a good reason to revisit my thinking. </p> <p> Could I have been wrong? That certainly wouldn't be the first time, but even re-reading the article today, I find my logic sound. Yet, I've substantially nuanced my position since then. </p> <p> It took me some time to understand how I could disagree so radically with people I respect. It didn't take me five years, though, but while I've been at peace with the apparent conflict for years, I've never written a coherent description of my current understanding of this problem space. This article is my attempt to remedy that omission. </p> <h3 id="eb43b60a35394df6b812514ac794cefe"> Context matters <a href="#eb43b60a35394df6b812514ac794cefe" title="permalink">#</a> </h3> <p> Whenever you consult an expert about how to address a problem, you'll invariably get the answer that <em>it depends</em>. I'd suggest that if you don't get that answer, the person is probably not an expert, after all. A useful expert will also be able to tell you on <em>what</em> 'it' depends. </p> <p> In an abstract sense, what 'it' depends on is <em>the context</em>. </p> <p> I wrote my original piece from a particular context. Part of that context is explicitly present in the article, but another part is entirely implicit. People read the article from within their own contexts, which in many cases turned out to be incongruent with mine. No wonder people disagreed. </p> <h3 id="9181a2688ce042d882cfe73a3bfed57e"> Watching the wildlife <a href="#9181a2688ce042d882cfe73a3bfed57e" title="permalink">#</a> </h3> <p> My context at that time was that I had some success with <a href="https://github.com/AutoFixture/AutoFixture">AutoFixture</a>, an open source library, which is what I consider <a href="http://blog.ploeh.dk/2012/12/18/RangersandZookeepers">wildlife</a> software. Once you've released a version of the software, you have no control of where it's installed, or how it's used. </p> <p> This means that backwards compatibility becomes important. If I broke something, I would inconvenience the users of my software. Making sure that compatibility didn't break became one of my highest priorities. I used unit tests for regression tests, and I did, indeed, test the entire public API of AutoFixture, to make sure that no breaking changes were introduced. </p> <p> That was my implicit context. Read in that light, my dogmatic insistence on testing everything hopefully makes a little more sense. </p> <p> Does that mean that my conclusion transfers to other circumstances? No, of course it doesn't. If you're developing and maintaining <a href="http://blog.ploeh.dk/2012/12/18/RangersandZookeepers">zoo software</a>, breaking changes are of less concern. From that perspective, my article could easily look like the creation of an unhinged mind. </p> <h3 id="a15643275c1a4d7ab484cacafa53b7da"> The purpose of tests <a href="#a15643275c1a4d7ab484cacafa53b7da" title="permalink">#</a> </h3> <p> In order to figure out what to test, and what not to test, you should ask yourself the question: <em>what's the purpose of testing?</em> </p> <p> At first glance, that may seem like an inane question, but there's actually more than one purpose of a unit test. When doing TDD, the purpose of a test is to provide feedback about the API you're developing. <a href="http://blog.ploeh.dk/2011/11/10/TDDimprovesreusability">A unit test is the first client of the production API</a>. If a test is difficult to write, the production API is difficult to use. More on TDD later, though. </p> <p> You may say that another purpose of automated tests is that they prevent errors. That's not the case, though. Automated tests prevent <em>regressions</em>. </p> <p> If you wrote the correct test, your test suite may also help to prevent errors, but a unit test is only as good as the programmer who wrote it. You could have made a mistake when you wrote the test. Or perhaps you misunderstood the specification of what you were trying to implement. <a href="http://blog.ploeh.dk/2013/04/02/why-trust-tests">Why do you even trust tests?</a> </p> <h3 id="d5b17ea45ed741899002d50fbb3e98c9"> The cost of regressions <a href="#d5b17ea45ed741899002d50fbb3e98c9" title="permalink">#</a> </h3> <p> Why do you want to prevent regressions? Because they're costly? </p> <p> Based on the little risk management I know about, you operate with two dimensions of risk: the impact of an event, should it occur, and the probability that the event occurs. </p> <p> Should we all be worried that an asteroid will hit the Earth and wipe out most life? The impact of such an event is truly catastrophic, yet the probability is diminishingly small, so the <em>risk</em> is insignificant. The risk of going for a drive in a car is much higher. </p> <p> How do you reduce risk? You either decrease the probability that the adverse event will happen, or you reduce the impact of it, should it happen. </p> <p> <a href="http://www.higherorderlogic.com/">Steve Freeman</a> once wrote a nice article about the distinction between fail-safe software, and software that could safely fail. Unfortunately, that article seems to have disappeared from the internet. The point, however, was that with unit tests, we attempt to make our software fail-safe. The unit tests act as a gate that prevents bad versions of the software from being released. That's not a bad strategy for managing risk, but only half of the strategies available. </p> <p> For example, <a href="http://amzn.to/1axt5YA">Continuous Delivery</a> describes how you can use <a href="https://martinfowler.com/bliki/CanaryRelease.html">Canary Releases</a> and automated rollbacks to reduce the impact of errors. That's what Steve Freeman called <em>safe fail</em>. </p> <p> I apologise for this detour around risk management, but I think that it's important that you make an explicit decision about automated testing. You can use unit tests to prevent regressions. What's the impact of an error in production, though? </p> <p> This depends on the type of software you're developing. When considering alternatives, I often envision the various options as inhabiting a continuum: </p> <p> <img src="/content/binary/test-coverage-continuum.png" alt="Test coverage continuum; no coverage to the left, maximum coverage to the right."> </p> <p> For some types of software, an error 'in production' could be fatal. This would be the case for guidance software for <a href="https://en.wikipedia.org/wiki/Voyager_1">Voyager 1</a>, <a href="https://en.wikipedia.org/wiki/Voyager_2">2</a>, other guidance software, software for medical devices, and so on. If you deploy a defect to Voyager 2, you've probably lost the craft for ever. </p> <p> (I'd be surprised if the Voyager guidance software is actually covered by unit tests, but I'd expect that other quality assurance checks are in place. For comparison, the space shuttle software development process has been appraised at CMMI level 5.) </p> <p> On the other side of the continuum, as a software developer, you probably write small ad-hoc development tools for your own use. For example, a few years ago I did a lot of <a href="https://en.wikipedia.org/wiki/Representational_state_transfer">REST</a> API development, and many of the APIs I worked with required <a href="https://en.wikipedia.org/wiki/OAuth">OAuth</a> authentication. I wrote a little command-line program that I could use to log on to an internal system and exchange that to a token. I don't think that I wrote any tests for that program. If there were problems with it, I'd just open the source code and fix the problem. Errors were cheap in that situation. </p> <p> Most software probably falls somewhere in the middle of those extremes. The cost of errors in wildlife software is probably higher than it is for zoo software, but most software can get by with less coverage than <em>everything</em>. </p> <h3 id="7db262526ca2459b813c0fda4f1e6999"> Cyclomatic complexity <a href="#7db262526ca2459b813c0fda4f1e6999" title="permalink">#</a> </h3> <p> How do you know that your software works? You test it. If you want to automate your testing efforts, you write unit tests... but a unit test suite is software. How do you know that your tests work? Is it going to be <a href="https://en.wikipedia.org/wiki/Turtles_all_the_way_down">turtles all the way down</a>? </p> <p> I think that we can <a href="http://blog.ploeh.dk/2013/04/02/why-trust-tests">trust tests for other reasons</a>, but one of them is that each test case exercises a deterministic path through a unit that supports many paths of execution. </p> <p> <img src="/content/binary/one-test-path-through-complex-unit.png" alt="Diagram that shows a unit test exercising one path through a unit."> </p> <p> In other words, each unit test is an example of a singular execution path. Tests, then, should have a <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity">cyclomatic complexity</a> of 1. In other words, you write (test) code with a cyclomatic complexity of 1 in order to test code with a higher cyclomatic complexity. </p> <p> Should you test code that has a cyclomatic complexity of 1? </p> <p> What would be the point of that? Why would you write a unit test with a cyclomatic complexity of 1 to test a piece of code with a cyclomatic complexity of 1? Wouldn't you just be adding more code? </p> <p> From the perspective of <em>trusting</em> the code, there's no reason to trust such a test more than the code that it exercises. In that light, I think it makes sense to <em>not</em> write that test. </p> <p> To be clear, there could be other reasons to test code with a cyclomatic complexity of 1. One reason, that I pointed out in my original article, is that you don't know if the simple piece of code will <em>stay</em> simple. Another reason is to prevent regressions. A common metaphor for unit testing is <a href="http://en.wikipedia.org/wiki/Double-entry_bookkeeping_system">double-entry bookkeeping</a>. If you write the unit test in a different way than the implementation, the two views on that behaviour may keep each other in check. You could do that with triangulation using <a href="http://xunitpatterns.com/Parameterized%20Test.html">parametrised tests</a>, or perhaps with property-based testing. </p> <p> I tend to use a heuristic where the farther to the left I am on the above continuum, the more I'm inclined to skip testing of simple functionality. Code with a cyclomatic complexity of 1 falls into that bucket. </p> <h3 id="5899a274dd0f4697b86772d3d0a5d6ce"> TDD <a href="#5899a274dd0f4697b86772d3d0a5d6ce" title="permalink">#</a> </h3> <p> Let's return our attention to TDD. The previous paragraphs have mostly discussed automated tests as a way to prevent regressions. TDD gives us an entirely different motivation for writing tests: the tests provide feedback on the design of our production code. </p> <p> Viewed like this, the tests themselves are only artefacts of the TDD process. It's usually a good idea to keep them around after the standard red-green-refactor cycle, because they serve double-duty as regression tests. </p> <p> Should you test-drive everything? If you're inexperienced with TDD, you get the best exercise by test-driving as much as possible. This still doesn't have to mean that you must write a an explicit test case for each class member. That's what both Mark Rendle and Derick Bailey pointed out. It's often enough if the tests somehow exercise those members. </p> <p> Revisiting my old article, my mistake was that I conflated TDD with regression testing. My motivation for writing an explicit test case for each member, no matter how trivial, was to preserve backwards compatibility. It really had nothing to do with TDD. </p> <h3 id="f0834719ee414d7e81a32c7cb32e8256"> When in doubt <a href="#f0834719ee414d7e81a32c7cb32e8256" title="permalink">#</a> </h3> <p> Despite all other rules of thumb I've so far listed, I'll suggest a few exceptions. </p> <p> Even if a piece of code theoretically has a cyclomatic complexity of 1, if you're in doubt of how it works, then write a test. </p> <p> If you have a defect in production, then reproduce that defect with one or more tests, even if the code in question is 'trivial'. Obviously, it wasn't trivial after all, if it caused a bug in production. </p> <h3 id="51cfec77312e45f7a2dd60b55096ba17"> Pragmatism <a href="#51cfec77312e45f7a2dd60b55096ba17" title="permalink">#</a> </h3> <p> When you're leaning something new, you're typically struggling with even the most basic concepts. That's just how learning works. In that phase of learning, it often pays to follow explicit rules. A way to think about this is the <a href="http://en.wikipedia.org/wiki/Dreyfus_model_of_skill_acquisition">Dreyfus model of skill acquisition</a>. Once you gain some experience, you can start deviating from the rules. We could call this <em>pragmatism</em>. </p> <p> I often discuss TDD with people who plead for pragmatism. Those people have typically practised TDD for years, if not decades. So have I, and, believe it or not, I'm often quite pragmatic when I practice TDD 'for real'. This is, however, a prerogative of experience. <blockquote> You can only be pragmatic if you know how to be dogmatic. </blockquote> I use the concept of <em>dogmatism</em> as an antonym to <em>pragmatism</em>. I view pragmatism in programming as the choice of practical solutions over theoretical principles. It's a <em>choice</em>, which means that you must be aware of alternatives. </p> <p> If you don't know the (principled) alternative, there's no choice. </p> <p> When you're learning something new, you're still not aware of how to do things according to principle. That's natural. I find myself in that situation all the time. If you keep at it, though, eventually you'll have gained enough experience that you can make actual choices. </p> <p> This applies to TDD as well. When you're still learning TDD, stick to the principles, particularly when it's inconvenient. Once you've done TDD for a few years, you've earned the right to be pragmatic. </p> <h3 id="11ce36adfdeb4b8e8c6b640e28691aa0"> Conclusion <a href="#11ce36adfdeb4b8e8c6b640e28691aa0" title="permalink">#</a> </h3> <p> Which parts of your code base should you (unit) test? It Depends™. </p> <p> It depends on why you are unit testing, and on the cost of defects in production, and probably many other things I didn't think of. </p> <p> What's the purpose of tests? Are you using TDD to get feedback on your API design ideas? Or is the main purpose of tests to prevent regressions? Your answers to such questions should guide your decisions on how much to test. </p> <p> Recently, I've mostly been writing about topics related to computer science, such as the <a href="http://blog.ploeh.dk/2017/10/04/from-design-patterns-to-category-theory">relationships between various branches of mathematics to computation</a>. In such realms, laws apply, and answers tend to be either right or wrong. A piece like this article is different. </p> <p> This is fundamentally a deeply subjective essay. It's based on my experience with writing automated tests in various circumstances since 2003. I've tried to be as explicit about my context as possible, but I've most likely failed to identify one or more implicit assumptions or biases. I do, therefore, encourage comments. </p> <p> I wrote this commentary because people keep asking me about how much to test, and when. I suppose it's because they wish to learn from me, and I'm happy to share what I know, to the best of my ability. I have much to learn myself, though, so read this only as the partial, flawed, personal answer that it is. </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>. Applicative validation http://blog.ploeh.dk/2018/11/05/applicative-validation 2018-11-05T07:05:00+00:00 Mark Seemann <div id="post"> <p> <em>Validate input in applicative style for superior readability and composability.</em> </p> <p> This article is an instalment in <a href="http://blog.ploeh.dk/2018/10/01/applicative-functors">an article series about applicative functors</a>. It demonstrates how applicative style can be used to compose small validation functions to a larger validation function in such a way that no validation messages are lost, and the composition remains readable. </p> <p> All example code in this article is given in <a href="https://www.haskell.org">Haskell</a>. No <a href="https://fsharp.org">F#</a> translation is offered, because <a href="http://fsharpforfunandprofit.com">Scott Wlaschin</a> has an <a href="https://fsharpforfunandprofit.com/posts/elevated-world-3/#validation">equivalent example covering input validation in F#</a>. </p> <h3 id="789d9704d9a2434f8631d718e8be3f17"> JSON validation <a href="#789d9704d9a2434f8631d718e8be3f17" title="permalink">#</a> </h3> <p> In my <a href="http://blog.ploeh.dk/functional-architecture-with-fsharp">Pluralsight course about a functional architecture in F#</a>, you can see an example of an on-line restaurant reservation system. I often return to that example scenario, so for regular readers of this blog, it should be known territory. For newcomers, imagine that you've been asked to develop an HTTP-based API that accepts JSON documents containing restaurant reservations. Such a JSON document could look like this: </p> <p> <pre>{ &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;date&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;2017-06-27&nbsp;18:30:00+02:00&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;name&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;Mark&nbsp;Seemann&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;email&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;mark@example.com&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;quantity&quot;</span>:&nbsp;4 }</pre> </p> <p> It contains the date and time of the (requested) reservation, the email address and name of the person making the reservation, as well as the number of people who will be dining. Particularly, notice that the date and time is represented as a string value (specifically, in <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> format), since JSON has no built-in date and time data type. </p> <p> In Haskell, you can represent such a JSON document using a type like this: </p> <p> <pre><span style="color:blue;">data</span>&nbsp;<span style="color:#dd0000;">ReservationJson</span>&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">ReservationJson</span>&nbsp;{ &nbsp;&nbsp;<span style="color:#600277;">jsonDate</span>&nbsp;::&nbsp;String, &nbsp;&nbsp;<span style="color:#600277;">jsonQuantity</span>&nbsp;::&nbsp;Double, &nbsp;&nbsp;<span style="color:#600277;">jsonName</span>&nbsp;::&nbsp;String, &nbsp;&nbsp;<span style="color:#600277;">jsonEmail</span>&nbsp;::&nbsp;String&nbsp;} &nbsp;&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#a31515;">Eq</span>,&nbsp;<span style="color:#a31515;">Show</span>,&nbsp;<span style="color:#a31515;">Read</span>,&nbsp;<span style="color:#a31515;">Generic</span>)</pre> </p> <p> Haskell's strength is in its type system, so you should prefer to model a reservation using a strong type: </p> <p> <pre><span style="color:blue;">data</span>&nbsp;<span style="color:#dd0000;">Reservation</span>&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">Reservation</span>&nbsp;{ &nbsp;&nbsp;<span style="color:#600277;">reservationDate</span>&nbsp;::&nbsp;<span style="color:blue;">ZonedTime</span>, &nbsp;&nbsp;<span style="color:#600277;">reservationQuantity</span>&nbsp;::&nbsp;Int, &nbsp;&nbsp;<span style="color:#600277;">reservationName</span>&nbsp;::&nbsp;String, &nbsp;&nbsp;<span style="color:#600277;">reservationEmail</span>&nbsp;::&nbsp;String&nbsp;} &nbsp;&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#a31515;">Show</span>,&nbsp;<span style="color:#a31515;">Read</span>)</pre> </p> <p> Instead of modelling the date and time as a string, you model it as a <code>ZonedTime</code> value. Additionally, you should model quantity as an integer, since a floating point value doesn't make much sense. </p> <p> While you can always translate a <code>Reservation</code> value to a <code>ReservationJson</code> value, the converse doesn't hold. There are <code>ReservationJson</code> values that you can't translate to <code>Reservation</code>. Such <code>ReservationJson</code> values are invalid. </p> <p> You should write code to validate and translate <code>ReservationJson</code> values to <code>Reservation</code> values, if possible. </p> <h3 id="e71bff7b635a449eb05a503c75c4f887"> Specialised validations <a href="#e71bff7b635a449eb05a503c75c4f887" title="permalink">#</a> </h3> <p> The <code>ReservationJson</code> type is a complex type, because it's composed of multiple (four) elements of different types. You can easily define at least three validation rules that ought to hold: <ol> <li>You should be able to convert the <code>jsonDate</code> value to a <code>ZonedTime</code> value.</li> <li><code>jsonQuantity</code> must be a positive integer.</li> <li><code>jsonEmail</code> should look believably like an email address.</li> </ol> When you have a complex type where more than one validation rule applies, your code will be most readable and maintainable if you can write each rule as an independent function. </p> <p> In Haskell, people often use <code>Either</code> for validation, but instead of using <code>Either</code> directly, I'll introduce a specialised <code>Validation</code> type: </p> <p> <pre><span style="color:blue;">newtype</span>&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;e&nbsp;r&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;(<span style="color:#dd0000;">Either</span>&nbsp;e&nbsp;r)&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#a31515;">Eq</span>,&nbsp;<span style="color:#a31515;">Show</span>,&nbsp;<span style="color:#a31515;">Functor</span>) </pre> </p> <p> You'll notice that this is simply a redefinition of <code>Either</code>. Haskell can automatically derive its <code>Functor</code> instance with the <code>DeriveFunctor</code> language extension. </p> <p> My motivation for introducing a new type is that the way that <code>Either</code> is <code>Applicative</code> is not quite how I'd like it to be. Introducing a <code>newtype</code> enables you to change how a type behaves. More on that later. First, you can implement the three individual validation functions. </p> <h3 id="89e88d794a0449189eff92795a2bca04"> Date validation <a href="#89e88d794a0449189eff92795a2bca04" title="permalink">#</a> </h3> <p> If the JSON date value is an ISO 8601-formatted string, then you can parse it as a <code>ZonedTime</code>. In that case, you should return the <code>Right</code> case of <code>Validation</code>. If you can't parse the string into a <code>ZonedTime</code> value, you should return a <code>Left</code> value containing a helpful error message. </p> <p> <pre><span style="color:#600277;">validateDate</span>&nbsp;::&nbsp;String&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Validation</span>&nbsp;[String]&nbsp;<span style="color:blue;">ZonedTime</span> validateDate&nbsp;candidate&nbsp;<span style="color:#666666;">=</span> &nbsp;&nbsp;<span style="color:blue;">case</span>&nbsp;readMaybe&nbsp;candidate&nbsp;<span style="color:blue;">of</span> &nbsp;&nbsp;&nbsp;&nbsp;Just&nbsp;d&nbsp;&nbsp;<span style="color:#666666;">-&gt;</span>&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;<span style="color:#666666;">$</span>&nbsp;Right&nbsp;d &nbsp;&nbsp;&nbsp;&nbsp;Nothing&nbsp;<span style="color:#666666;">-&gt;</span>&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;<span style="color:#666666;">$</span>&nbsp;Left&nbsp;[<span style="color:#a31515;">&quot;Not&nbsp;a&nbsp;date.&quot;</span>]</pre> </p> <p> This function uses <code>readMaybe</code> from <code>Text.Read</code> to attempt to parse the <code>candidate</code> <code>String</code>. When <code>readMaybe</code> can read the <code>String</code> value, it returns a <code>Just</code> value with the parsed value inside; otherwise, it returns <code>Nothing</code>. The function pattern-matches on those two cases and returns the appropriate value in each case. </p> <p> Notice that errors are represented as a list of <code>String</code> values, although this particular function only returns a single message in its list of error messages. The reason for that is that you should be able to collect multiple validation issues for a complex value such as <code>ReservationJson</code>, and keeping track of errors in a list makes that possible. </p> <p> Haskell <a href="https://en.wikipedia.org/wiki/Code_golf">golfers</a> may argue that this implementation is overly verbose, and it could, for instance, instead be written as: </p> <p> <pre>validateDate&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;<span style="color:#666666;">.</span>&nbsp;maybe&nbsp;(Left&nbsp;[<span style="color:#a31515;">&quot;Not&nbsp;a&nbsp;date.&quot;</span>])&nbsp;Right&nbsp;<span style="color:#666666;">.</span>&nbsp;readMaybe </pre> </p> <p> which is true, but not as readable. Both versions get the job done, though, as these GCHi-based ad-hoc tests demonstrate: </p> <p> <pre>λ&gt; validateDate "2017/27/06 18:30:00 UTC+2" Validation (Left ["Not a date."]) λ&gt; validateDate "2017-06-27 18:30:00+02:00" Validation (Right 2017-06-27 18:30:00 +0200)</pre> </p> <p> That takes care of parsing dates. On to the next validation function. </p> <h3 id="df33c4c13805494b844793bac0577e5b"> Quantity validation <a href="#df33c4c13805494b844793bac0577e5b" title="permalink">#</a> </h3> <p> JSON numbers aren't guaranteed to be integers, so it's possible that even a well-formed Reservation JSON document could contain a <code>quantity</code> property of <code>9.7</code>, <code>-11.9463</code>, or similar. When handling restaurant reservations, however, it only makes sense to handle positive integers. Even <code>0</code> is useless in this context. Thus, validation must check for two conditions, so in principle, you could write two separate functions for that. In order to keep the example simple, though, I've included both tests in the same function: </p> <p> <pre><span style="color:#600277;">validateQuantity</span>&nbsp;::&nbsp;Double&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Validation</span>&nbsp;[String]&nbsp;Int validateQuantity&nbsp;candidate&nbsp;<span style="color:#666666;">=</span> &nbsp;&nbsp;<span style="color:#af00db;">if</span>&nbsp;isInt&nbsp;candidate&nbsp;<span style="color:#666666;">&amp;&amp;</span>&nbsp;candidate&nbsp;<span style="color:#666666;">&gt;</span>&nbsp;<span style="color:#09885a;">0</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#af00db;">then</span>&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;<span style="color:#666666;">$</span>&nbsp;Right&nbsp;<span style="color:#666666;">$</span>&nbsp;round&nbsp;candidate &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#af00db;">else</span>&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;<span style="color:#666666;">$</span>&nbsp;Left&nbsp;[<span style="color:#a31515;">&quot;Not&nbsp;a&nbsp;positive&nbsp;integer.&quot;</span>] &nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;isInt&nbsp;x&nbsp;<span style="color:#666666;">=</span>&nbsp;x&nbsp;<span style="color:#666666;">==</span>&nbsp;fromInteger&nbsp;(round&nbsp;x)</pre> </p> <p> If <code>candidate</code> is both an integer, and greater than zero, then <code>validateQuantity</code> returns <code>Right</code>; otherwise, it returns a <code>Left</code> value containing an error message. Like <code>validateDate</code>, you can easily test <code>validateQuantity</code> in GHCi: </p> <p> <pre>λ&gt; validateQuantity 4 Validation (Right 4) λ&gt; validateQuantity (-1) Validation (Left ["Not a positive integer."]) λ&gt; validateQuantity 2.32 Validation (Left ["Not a positive integer."])</pre> </p> <p> Perhaps you can think of rules for names, but I can't, so we'll leave the name be and move on to validating email addresses. </p> <h3 id="7eb2c9f79bfa4f7fa866094d094c5e2c"> Email validation <a href="#7eb2c9f79bfa4f7fa866094d094c5e2c" title="permalink">#</a> </h3> <p> It's <a href="http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx">notoriously difficult to validate SMTP addresses</a>, so you shouldn't even try. It seems fairly safe to assume, however, that an email address must contain at least one <code>@</code> character, so that's going to be all the validation you have to implement: </p> <p> <pre><span style="color:#600277;">validateEmail</span>&nbsp;::&nbsp;String&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Validation</span>&nbsp;[String]&nbsp;String validateEmail&nbsp;candidate&nbsp;<span style="color:#666666;">=</span> &nbsp;&nbsp;<span style="color:#af00db;">if</span>&nbsp;<span style="color:#a31515;">&#39;@&#39;</span>&nbsp;<span style="color:#666666;">`elem`</span>&nbsp;candidate &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#af00db;">then</span>&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;<span style="color:#666666;">$</span>&nbsp;Right&nbsp;candidate &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#af00db;">else</span>&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;<span style="color:#666666;">$</span>&nbsp;Left&nbsp;[<span style="color:#a31515;">&quot;Not&nbsp;an&nbsp;email&nbsp;address.&quot;</span>]</pre> </p> <p> Straightforward. Try it out in GHCI: </p> <p> <pre>λ&gt; validateEmail "foo" Validation (Left ["Not an email address."]) λ&gt; validateEmail "foo@example.org" Validation (Right "foo@example.org")</pre> </p> <p> Indeed, that works. </p> <h3 id="bcfce51ff4e94f79a6648a7e373ebc82"> Applicative composition <a href="#bcfce51ff4e94f79a6648a7e373ebc82" title="permalink">#</a> </h3> <p> What you really should be doing is to validate a <code>ReservationJson</code> value. You have the three validation rules implemented, so now you have to compose them. There is, however, a catch: you must evaluate all rules, and return a list of <em>all</em> the errors you encountered. That's probably going to be a better user experience for a user. </p> <p> That's the reason you can't use <code>Either</code>. While it's <code>Applicative</code>, it doesn't behave like you'd like it to behave in this scenario. Particularly, the problem is that it throws away all but the first <code>Left</code> value it finds: </p> <p> <pre>λ&gt; Right (,,) &lt;*&gt; Right 42 &lt;*&gt; Left "foo" &lt;*&gt; Left "bar" Left "foo"</pre> </p> <p> Notice how <code>Left "bar"</code> is ignored. </p> <p> With the new type <code>Validation</code> based on <code>Either</code>, you can now define how it behaves as an applicative functor: </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Monoid</span>&nbsp;m&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;<span style="color:blue;">Applicative</span>&nbsp;(<span style="color:blue;">Validation</span>&nbsp;m)&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;pure&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;<span style="color:#666666;">.</span>&nbsp;pure &nbsp;&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;(Left&nbsp;x)&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;(Left&nbsp;y)&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;(Left&nbsp;(mappend&nbsp;x&nbsp;y)) &nbsp;&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;f&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;r&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">Validation</span>&nbsp;(f&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;r)</pre> </p> <p> This instance is restricted to <code>Monoid</code> <code>Left</code> types. It has special behaviour for the case where both expressions passed to <code>&lt;*&gt;</code> are <code>Left</code> values. In that case, it uses <code>mappend</code> (from <code>Monoid</code>) to 'add' the two <code>Left</code> values together in a new <code>Left</code> value. </p> <p> For all other cases, this instance of <code>Applicative</code> delegates to the behaviour defined for <code>Either</code>. It also uses <code>pure</code> from <code>Either</code> to implement its own <code>pure</code> function. </p> <p> Lists (<code>[]</code>) <a href="http://blog.ploeh.dk/2017/10/10/strings-lists-and-sequences-as-a-monoid">form a monoid</a>, and since all the above validation functions return lists of errors, it means that you can compose them using this definition of <code>Applicative</code>: </p> <p> <pre><span style="color:#600277;">validateReservation</span>&nbsp;::&nbsp;<span style="color:blue;">ReservationJson</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Validation</span>&nbsp;[String]&nbsp;<span style="color:blue;">Reservation</span> validateReservation&nbsp;candidate&nbsp;<span style="color:#666666;">=</span> &nbsp;&nbsp;pure&nbsp;<span style="color:#dd0000;">Reservation</span>&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;vDate&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;vQuantity&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;vName&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;vEmail &nbsp;&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;&nbsp;&nbsp;vDate&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#666666;">=</span>&nbsp;validateDate&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#666666;">$</span>&nbsp;jsonDate&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;candidate &nbsp;&nbsp;&nbsp;&nbsp;vQuantity&nbsp;<span style="color:#666666;">=</span>&nbsp;validateQuantity&nbsp;<span style="color:#666666;">$</span>&nbsp;jsonQuantity&nbsp;candidate &nbsp;&nbsp;&nbsp;&nbsp;vName&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#666666;">=</span>&nbsp;pure&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#666666;">$</span>&nbsp;jsonName&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;candidate &nbsp;&nbsp;&nbsp;&nbsp;vEmail&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#666666;">=</span>&nbsp;validateEmail&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#666666;">$</span>&nbsp;jsonEmail&nbsp;&nbsp;&nbsp;&nbsp;candidate</pre> </p> <p> The <code>candidate</code> is a <code>ReservationJson</code> value, but each of the validation functions work on either <code>String</code> or <code>Double</code>, so you'll have to use the <code>ReservationJson</code> type's access functions (<code>jsonDate</code>, <code>jsonQuantity</code>, and so on) to pull the relevant values out of it. Once you have those, you can pass them as arguments to the appropriate validation function. </p> <p> Since there's no rule for <code>jsonName</code>, you can use <code>pure</code> to create a <code>Validation</code> value. All four resulting values (<code>vDate</code>, <code>vQuantity</code>, <code>vName</code>, and <code>vEmail</code>) are <code>Validation [String]</code> values; only their <code>Right</code> types differ. </p> <p> The <code>Reservation</code> record constructor is a function of the type <code>ZonedTime -&gt; Int -&gt; String -&gt; String -&gt; Reservation</code>, so when you arrange the four <code>v*</code> values correctly between the <code>&lt;*&gt;</code> operator, you have the desired composition. </p> <p> Try it in GHCi: </p> <p> <pre>λ&gt; validateReservation $ ReservationJson "2017-06-30 19:00:00+02:00" 4 "Jane Doe" "j@example.com" Validation (Right (Reservation { &nbsp;&nbsp;&nbsp;&nbsp;reservationDate = 2017-06-30 19:00:00 +0200, &nbsp;&nbsp;&nbsp;&nbsp;reservationQuantity = 4, &nbsp;&nbsp;&nbsp;&nbsp;reservationName = "Jane Doe", &nbsp;&nbsp;&nbsp;&nbsp;reservationEmail = "j@example.com"})) λ&gt; validateReservation $ ReservationJson "2017/14/12 6pm" 4.1 "Jane Doe" "jane.example.com" Validation (Left ["Not a date.","Not a positive integer.","Not an email address."]) λ&gt; validateReservation $ ReservationJson "2017-06-30 19:00:00+02:00" (-3) "Jane Doe" "j@example.com" Validation (Left ["Not a positive integer."])</pre> </p> <p> The first <code>ReservationJson</code> value passed to <code>validateReservation</code> is valid, so the return value is a <code>Right</code> value. </p> <p> The next <code>ReservationJson</code> value is about as wrong as it can be, so three different error messages are returned in a <code>Left</code> value. This demonstrates that <code>Validation</code> doesn't give up the first time it encounters a <code>Left</code> value, but rather collects them all. </p> <p> The third example demonstrates that even a single invalid value (in this case a negative quantity) is enough to make the entire input invalid, but as expected, there's only a single error message. </p> <h3 id="b9d3fd6c208647dc988ef0ffc64cf061"> Summary <a href="#b9d3fd6c208647dc988ef0ffc64cf061" title="permalink">#</a> </h3> <p> Validation may be the poster child of applicative functors, but it <em>is</em> a convenient way to solve the problem. In this article you saw how to validate a complex data type, collecting and reporting on all problems, if any. </p> <p> In order to collect all errors, instead of immediately short-circuiting on the first error, you have to deviate from the standard <code>Either</code> implementation of <code>&lt;*&gt;</code>. If you go back to read Scott Wlaschin's article, you should be aware that it specifically implements its applicative functor in that way, instead of the normal behaviour of <code>Either</code>. </p> <p> More applicative functors exist. This article series has, I think, room for more examples. </p> <p> <strong>Next:</strong> The Test Data Generator applicative functor. </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 applicative functor http://blog.ploeh.dk/2018/10/29/the-maybe-applicative-functor 2018-10-29T06:17:00+00:00 Mark Seemann <div id="post"> <p> <em>An introduction to the Maybe applicative functor for object-oriented programmers.</em> </p> <p> This article is an instalment in <a href="http://blog.ploeh.dk/2018/10/01/applicative-functors">an article series about applicative functors</a>. Previously, in a related series, you got an introduction to <a href="http://blog.ploeh.dk/2018/03/26/the-maybe-functor">Maybe as a functor</a>. Not all functors are applicative, but some are, and Maybe is one of them (like list). </p> <p> In this article, you'll see how to make a C# Maybe class applicative. While I'm going to start with <a href="https://fsharp.org">F#</a> and <a href="https://www.haskell.org">Haskell</a>, you can skip to the C# section if you'd like. </p> <h3 id="f88a2d0afbe84b7695fe4247e3cfe941"> F# <a href="#f88a2d0afbe84b7695fe4247e3cfe941" title="permalink">#</a> </h3> <p> A few years ago, <a href="http://blog.ploeh.dk/2016/06/28/roman-numerals-via-property-based-tdd">I did the <em>Roman numerals</em> kata</a> in F#. This is an exercise where you have to convert between normal base 10 integers and <a href="https://en.wikipedia.org/wiki/Roman_numerals">Roman numerals</a>. Conversions can fail in both directions, because Roman numerals don't support negative numbers, zero, or numbers greater than 3,999, and Roman numerals represented as strings could be malformed. </p> <p> Some Roman numbers are written in a subtractive style, e.g. "IV" means <em>subtract 1 (I) from 5 (V)</em>. It's easy enough to subtract two numbers, but because parsing isn't guaranteed to succeed, I didn't have two numbers; I had two number <em>options</em> (recall that in F#, Maybe is called <code>option</code>). </p> <p> How do you subtract one <code>int option</code> from another <code>int option</code>? </p> <p> Both of these values could be <code>Some</code>, or they could be <code>None</code>. What should happen in each case? With Maybe, only four combinations are possible, so you can put them in a table: <table> <thead> <tr> <th></th> <th><code>Some x</code></th> <th><code>None</code></th> </tr> </thead> <tbody> <tr> <td><strong><code>Some y</code></strong></td> <td><code>Some (x - y)</code></td> <td><code>None</code></td> </tr> <tr> <td><strong><code>None</code></strong></td> <td><code>None</code></td> <td><code>None</code></td> </tr> </tbody> </table> Only if both values are <code>Some</code> cases should you return a <code>Some</code> case with the result of the subtraction; in all other cases, you should return <code>None</code>. </p> <p> You can do this with regular pattern matching, but it's hardly the most elegant solution: </p> <p> <pre><span style="color:green;">//&nbsp;int&nbsp;option</span> <span style="color:blue;">let</span>&nbsp;difference&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;minuend,&nbsp;subtrahend&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:navy;">Some</span>&nbsp;m,&nbsp;<span style="color:navy;">Some</span>&nbsp;s&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:navy;">Some</span>&nbsp;(m&nbsp;-&nbsp;s) &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;<span style="color:navy;">None</span></pre> </p> <p> You <em>could</em> attempt to solve this with a specialised helper function like this: </p> <p> <pre><span style="color:blue;">module</span>&nbsp;<span style="color:teal;">Option</span>&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;(&#39;a&nbsp;-&gt;&nbsp;&#39;b&nbsp;-&gt;&nbsp;&#39;c)&nbsp;-&gt;&nbsp;&#39;a&nbsp;option&nbsp;-&gt;&nbsp;&#39;b&nbsp;option&nbsp;-&gt;&nbsp;&#39;c&nbsp;option</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;<span style="color:navy;">map2</span>&nbsp;<span style="color:navy;">f</span>&nbsp;xo&nbsp;yo&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;xo,&nbsp;yo&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:navy;">Some</span>&nbsp;x,&nbsp;<span style="color:navy;">Some</span>&nbsp;y&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:navy;">Some</span>&nbsp;(<span style="color:navy;">f</span>&nbsp;x&nbsp;y) &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;">-&gt;</span>&nbsp;<span style="color:navy;">None</span></pre> </p> <p> which you could use like this: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;difference&nbsp;=&nbsp;<span style="color:teal;">Option</span>.<span style="color:navy;">map2</span>&nbsp;(-)&nbsp;minuend&nbsp;subtrahend </pre> </p> <p> It doesn't, however, generalise well... What if you need to operate on three option values, instead of two? Or four? Should you add <code>map3</code> and <code>map4</code> functions as well? </p> <p> Making <code>option</code> an applicative functor addresses that problem. Here's one possible implementation of <code>&lt;*&gt;</code>: </p> <p> <pre><span style="color:green;">//&nbsp;(&#39;a&nbsp;-&gt;&nbsp;&#39;b)&nbsp;option&nbsp;-&gt;&nbsp;&#39;a&nbsp;option&nbsp;-&gt;&nbsp;&#39;b&nbsp;option</span> <span style="color:blue;">let</span>&nbsp;(&lt;*&gt;)&nbsp;fo&nbsp;xo&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;fo,&nbsp;xo&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:navy;">Some</span>&nbsp;<span style="color:navy;">f</span>,&nbsp;<span style="color:navy;">Some</span>&nbsp;x&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:navy;">Some</span>&nbsp;(<span style="color:navy;">f</span>&nbsp;x) &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;<span style="color:navy;">None</span></pre> </p> <p> This enables you two write the subtraction like this: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;difference&nbsp;=&nbsp;<span style="color:navy;">Some</span>&nbsp;(-)&nbsp;&lt;*&gt;&nbsp;minuend&nbsp;&lt;*&gt;&nbsp;subtrahend </pre> </p> <p> For a detailed explanation on how that works, see the <a href="http://blog.ploeh.dk/2018/10/08/full-deck">previous explanation for lists</a>; it works the same way for Maybe as it does for List. </p> <p> In the end, however, I didn't think that this was the most readable code, so in the Roman numeral exercise, I chose to use a <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/computation-expressions">computation expression</a> instead. </p> <h3 id="264aaa993b7643b692716bed1b3e2b92"> Haskell <a href="#264aaa993b7643b692716bed1b3e2b92" title="permalink">#</a> </h3> <p> In Haskell, <code>Maybe</code> is already <code>Applicative</code> as part of the language. Without further ado, you can simply write: </p> <p> <pre>difference&nbsp;<span style="color:#666666;">=</span>&nbsp;pure&nbsp;<span style="color:#600277;">(-)</span>&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;minuend&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;subtrahend </pre> </p> <p> As is the case with the F# code, I don't consider this the most <em>readable</em> way to express the subtraction of two integers. In F#, I ultimately decided to use a computation expression. In Haskell, that's equivalent to using <code>do</code> notation: </p> <p> <pre><span style="color:#600277;">difference</span>&nbsp;::&nbsp;Maybe&nbsp;Integer difference&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#af00db;">do</span> &nbsp;&nbsp;m&nbsp;<span style="color:#666666;">&lt;-</span>&nbsp;minuend &nbsp;&nbsp;s&nbsp;<span style="color:#666666;">&lt;-</span>&nbsp;subtrahend &nbsp;&nbsp;return&nbsp;<span style="color:#666666;">$</span>&nbsp;m&nbsp;<span style="color:#666666;">-</span>&nbsp;s</pre> </p> <p> While more verbose, I think it's clearer that one number is being subtracted from another number. </p> <p> This works for <code>Maybe</code> because not only is <code>Maybe</code> <code>Applicative</code>, it's also a <code>Monad</code>. It's its monadness that enables the <code>do</code> notation. Not all applicative functors are monads, but Maybe is. </p> <h3 id="67a752fec39f4944984f505c125632f1"> C# <a href="#67a752fec39f4944984f505c125632f1" title="permalink">#</a> </h3> <p> In a <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#. You can extend it so that it also becomes an applicative functor: </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;">TResult</span>&gt;&nbsp;Apply&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;">Maybe</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;selector, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;source) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(selector.HasItem&nbsp;&amp;&amp;&nbsp;source.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;">TResult</span>&gt;(selector.Item(source.Item)); &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;">Maybe</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;(); } <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;">Func</span>&lt;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;Apply&lt;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;selector, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Maybe</span>&lt;<span style="color:#2b91af;">T1</span>&gt;&nbsp;source) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(selector.HasItem&nbsp;&amp;&amp;&nbsp;source.HasItem) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;g&nbsp;=&nbsp;x&nbsp;=&gt;&nbsp;selector.Item(source.Item,&nbsp;x); &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;">Func</span>&lt;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;(g); &nbsp;&nbsp;&nbsp;&nbsp;} &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;">Maybe</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;(); }</pre> </p> <p> As was the case for making sequences applicative in C#, you <a href="http://blog.ploeh.dk/2018/10/15/an-applicative-password-list">need overloads of the <code>Apply</code> method</a>, because C#'s type inference is inadequate for this task. </p> <p> If you have two <code>Maybe&lt;int&gt;</code> values, <code>minuend</code> and <code>subtrahend</code>, you can now perform the subtraction: </p> <p> <pre><span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;subtract&nbsp;=&nbsp;(x,&nbsp;y)&nbsp;=&gt;&nbsp;x&nbsp;-&nbsp;y; <span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;difference&nbsp;=&nbsp;subtract.ToMaybe().Apply(minuend).Apply(subtrahend);</pre> </p> <p> Like in F# and Haskell, applicative style is hardly the most readable way to express subtraction. It'd be nice if you could write it like Haskell's <code>do</code> notation. You can, but to do that, you must make Maybe a monad, and this isn't a monad tutorial. <a href="http://mikehadlow.com">Mike Hadlow</a> has a good <a href="http://mikehadlow.blogspot.dk/2011/01/monads-in-c1-introduction.html">monad tutorial for C# developers</a>, the gist of which is that you must implement <code>SelectMany</code> in order to turn your generic type into a monad. For now, I'll leave this as an exercise for you, but if you add an appropriate <code>SelectMany</code> method, you'd be able to write the subtraction like this: </p> <p> <pre><span style="color:#2b91af;">Maybe</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;difference&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;m&nbsp;<span style="color:blue;">in</span>&nbsp;minuend &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;s&nbsp;<span style="color:blue;">in</span>&nbsp;subtrahend &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;m&nbsp;-&nbsp;s;</pre> </p> <p> Again, I think this is more readable, but it does require that the type in question is a monad, and not all applicative functors are (but Maybe is). </p> <h3 id="b03175fcd3a74155a3ceac26fb02aed0"> Summary <a href="#b03175fcd3a74155a3ceac26fb02aed0" title="permalink">#</a> </h3> <p> This article demonstrates that lists or sequences aren't the only applicative functors. Maybe is also an applicative functor, but more exist. The next article will give you another example. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/11/05/applicative-validation">Applicative validation</a>. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="d42afea512c243019f500a345638cecb"> <div class="comment-author">Tyson Williams</div> <div class="comment-content"> <blockquote> As was the case for making sequences applicative in C#, you <a href="http://blog.ploeh.dk/2018/10/15/an-applicative-password-list">need overloads of the <code>Apply</code> method</a>, because C#'s type inference is inadequate for this task. </blockquote> <p> I think <a href=http://blog.ploeh.dk/2018/10/15/an-applicative-password-list/#b4e76681ea894aa3be1e6b836343c148">we agreed</a> that the issue is not C#'s weak type inference but its lack of default function currying? My guess is that you wrote this quoted part of this article before my comment on your previous article. </p> </div> <div class="comment-date">2018-11-06 02:44 UTC</div> </div> <div class="comment" id="0bb16509bbea463bab48c9e97acea2c5"> <div class="comment-author"><a href="http://blog.ploeh.dk">Mark Seemann</a></div> <div class="comment-content"> <p> Tyson, thank you for writing. <blockquote> "My guess is that you wrote this quoted part of this article before my comment on your previous article." </blockquote> Yes, <a href="https://github.com/ploeh/ploeh.github.com/commit/078cb3e938bfb911363cc8ab1139dfc5ad435349">June 27, 2017, in fact</a>... </p> <p> You're correct that this particular issue is related to the uncurried nature of C# methods. </p> <p> I do, however, maintain that C#'s type inference capabilities are weaker than F#'s or Haskell's. To be clear, I view this as the result of priorities. I don't think that the people who designed and wrote the C# compiler are less skilled than the designers of F# or Haskell. The C# compiler has to solve many other problems, such as for example overload resolution, which is a language feature in direct opposition to currying. The C# compiler is excellent at overload resolution, a task with which the F# compiler sometimes struggle (and is not even a language feature in Haskell). </p> <p> Your comment is, however, a reminder that I should consider how I phrase such notions in the future. Thank you for pointing that out. As I'm publishing and get feedback, I constantly learn new things. I'm always grateful when someone like you take the time to educate me. </p> <p> I'll see if I can improve in the future. I do, however, still have a backlog of articles I wrote months, or even more than a year, ago, so it's possible that more errors escape my attention when I proof read them before publication. If that happens, I'll appreciate more corrections. </p> </div> <div class="comment-date">2018-11-06 7:30 UTC</div> </div> <div class="comment" id="01d5086d3f9a4d93ad4bea131521bafa"> <div class="comment-author">Tyson Williams</div> <div class="comment-content"> <p> Thank you very much for your kind reply. I agree with everything you said. </p> <p> I will expand my comment a bit to give a clearer picture of my understanding. </p> <p> First, very little is "needed"; most things are merely sufficient. In particular, we don't <i>need</i> to overload your <code>Apply</code> method to achieve your goal. As <a href="http://blog.ploeh.dk/2018/10/15/an-applicative-password-list/#0ded7ac93aad8ba7b1063dd49c2051f1">I mentioned before</a>, it sufficies to have a single <code>Apply</code> method and instead create overloads of a function called <code>curry</code> that explicitly curries a given function. Furthermore, I think there is a sense in which this latter approach to overcome the lack of default currying is somehow minimal or most abstract or most general. </p> <p> Second, compared to languages like F# or Haskell, type inference is definitely weaker in C#. This issue was also present (in a subtle way) in your previous article, but I decided to largely ignore it in order to keep my comment more focused. In your <a href="http://blog.ploeh.dk/2018/10/15/an-applicative-password-list/">previous article</a>, you expliciltly defined the local variable <code>concat</code> like this <blockquote> <pre><span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;concat&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;(x,&nbsp;y,&nbsp;z,&nbsp;æ,&nbsp;ø,&nbsp;å)&nbsp;=&gt;&nbsp;x&nbsp;+&nbsp;y&nbsp;+&nbsp;z&nbsp;+&nbsp;æ&nbsp;+&nbsp;ø&nbsp;+&nbsp;å;</pre> </blockquote> In particular, you explicitly told the C# compiler that the type of all of these six variable is <code><span style="color:blue;">string</span></code>. That part was necessary; the type inference in C# is not strong enough to innfer (possibily in some use of <code>concat</code>) that the types could be <code><span style="color:blue;">string</span></code>. </p> <p> Suppose instead of defining <code>concat</code> as a local variable (with <code><span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;</code> as its type) you had defined it as a member method on a class. Then its type in C# is some kind "method group". The method group of a method essentially corresponds to the set of methods containing itself and its overloads. Then in order to pass <code>concat</code> into <code>curry</code>, there needs to be a type conversion (or cast) from its method group to <code><span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;</code>. This is also something that the C# system cannot do, and so Language Ext has overloads of a <a href="https://github.com/louthy/language-ext/blob/master/LanguageExt.Core/Prelude/Prelude_Func.cs#L24">function called <code>fun</code></a> to do this explicitly. Using it on our hypothetical member function <code>concat</code> would look like <pre>fun&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;(concat)</pre> Again, I think there is a sense in which this explicit way to specify non-inferable types is somehow minimal or most abstract or most general. </p> <p> My impression is that there is some low hanging fruit here for strengthing the type inference of the C# compiler. If a method group correpsonds to a singleton set (and that method has no <code>ref</code> or <code>out</code> arguments), then I would think it would be straight forward to consider an implicit cast from the method group to the corresponding <code>Func</code> or <code>Action</code> delegate. </p> </div> <div class="comment-date">2018-11-06 15:31 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>. Applicative combinations of functions http://blog.ploeh.dk/2018/10/22/applicative-combinations-of-functions 2018-10-22T10:21:00+00:00 Mark Seemann <div id="post"> <p> <em>Applicative lists and sequences enable you to create combinations of functions as well as values.</em> </p> <p> This article is an instalment in <a href="http://blog.ploeh.dk/2018/10/01/applicative-functors">an article series about applicative functors</a>. In the <a href="http://blog.ploeh.dk/2018/10/15/an-applicative-password-list">previous article</a>, you saw how you can use applicative lists and sequences to generate combinations of values; specifically, the example demonstrated how to generate various password character combinations. </p> <p> People often create passwords by using a common word as basis, and then turn characters into upper- or lower case. Someone feeling particularly tech-savvy may replace certain characters with digits, in an imitation of <a href="https://en.wikipedia.org/wiki/Leet">1337</a>. While this isn't secure, let's look at how to create various combinations of transformations using applicative lists and sequences. </p> <h3 id="302fedff3eed4c09b277bd4ee3523ff3"> List of functions <a href="#302fedff3eed4c09b277bd4ee3523ff3" title="permalink">#</a> </h3> <p> In the previous article, I mentioned that there was a feature of applicative lists that I had, so far, deliberately ignored. </p> <p> If you consider an example like this: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;passwordCombinations&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;[<span style="color:navy;">sprintf</span>&nbsp;<span style="color:#a31515;">&quot;</span><span style="color:teal;">%s%s%s%s%s%s</span><span style="color:#a31515;">&quot;</span>] &nbsp;&nbsp;&nbsp;&nbsp;&lt;*&gt;&nbsp;[<span style="color:#a31515;">&quot;P&quot;</span>;&nbsp;<span style="color:#a31515;">&quot;p&quot;</span>]&nbsp;&lt;*&gt;&nbsp;[<span style="color:#a31515;">&quot;a&quot;</span>;&nbsp;<span style="color:#a31515;">&quot;4&quot;</span>]&nbsp;&lt;*&gt;&nbsp;[<span style="color:#a31515;">&quot;ssw&quot;</span>]&nbsp;&lt;*&gt;&nbsp;[<span style="color:#a31515;">&quot;o&quot;</span>;&nbsp;<span style="color:#a31515;">&quot;0&quot;</span>]&nbsp;&lt;*&gt;&nbsp;[<span style="color:#a31515;">&quot;rd&quot;</span>]&nbsp;&lt;*&gt;&nbsp;[<span style="color:#a31515;">&quot;&quot;</span>;&nbsp;<span style="color:#a31515;">&quot;!&quot;</span>]</pre> </p> <p> you may have already noticed that while the left side of the <code>&lt;*&gt;</code> operator is a list of functions, it contains only a single function. What happens if you supply more than a single function? </p> <p> You get a combination of each function and each list element. </p> <p> Assume that you have three functions to convert characters: </p> <p> <pre><span style="color:blue;">module</span>&nbsp;<span style="color:teal;">Char</span>&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;char&nbsp;-&gt;&nbsp;char</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;<span style="color:navy;">toUpper</span>&nbsp;c&nbsp;=&nbsp;System.<span style="color:teal;">Char</span>.<span style="color:navy;">ToUpperInvariant</span>&nbsp;c &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;char&nbsp;-&gt;&nbsp;char</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;<span style="color:navy;">toLower</span>&nbsp;c&nbsp;=&nbsp;System.<span style="color:teal;">Char</span>.<span style="color:navy;">ToLowerInvariant</span>&nbsp;c &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;Not&nbsp;even&nbsp;trying&nbsp;to&nbsp;be&nbsp;complete:</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;char&nbsp;-&gt;&nbsp;char</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;<span style="color:navy;">to1337</span>&nbsp;=&nbsp;<span style="color:blue;">function</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:#a31515;">&#39;a&#39;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:#a31515;">&#39;A&#39;</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#a31515;">&#39;4&#39;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:#a31515;">&#39;b&#39;</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#a31515;">&#39;6&#39;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:#a31515;">&#39;E&#39;</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#a31515;">&#39;3&#39;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:#a31515;">&#39;H&#39;</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#a31515;">&#39;#&#39;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:#a31515;">&#39;i&#39;</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#a31515;">&#39;!&#39;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:#a31515;">&#39;l&#39;</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#a31515;">&#39;1&#39;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:#a31515;">&#39;o&#39;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:#a31515;">&#39;O&#39;</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#a31515;">&#39;0&#39;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:#a31515;">&#39;t&#39;</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#a31515;">&#39;+&#39;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;c&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;c</pre> </p> <p> All three are functions that convert one <code>char</code> value to another, although many values could pass through without being modified. Since they all have the same type, you can create a list of them: </p> <p> <pre>&gt; List.map String.map [Char.toUpper; Char.toLower; Char.to1337] &lt;*&gt; ["Hello"; "World"];; val it : string list = ["HELLO"; "WORLD"; "hello"; "world"; "#e110"; "W0r1d"]</pre> </p> <p> There's a bit to unpack there. Recall that all three functions in the <code>Char</code> module have the same type: <code>char -&gt; char</code>. Making a list of them gives you a <code>(char -&gt; char) list</code>, but you really need a <code>(string -&gt; string) list</code>. Fortunately, the built-in <code>String.map</code> function takes a <code>char -&gt; char</code> function and uses it to map each <code>char</code> values in a <code>string</code>. Thus, <code>List.map String.map [Char.toUpper; Char.toLower; Char.to1337]</code> gives you a <code>(string -&gt; string) list</code>. </p> <p> When you apply (<code>&lt;*&gt;</code>) that list of functions with a list of <code>string</code> values, you get all possible combinations of each function used with each string. Both <code>"Hello"</code> and <code>"World"</code> are converted to upper case, lower case, and 1337. </p> <h3 id="fde27240cfaf4479bc31ff50d3f619d0"> Combinations of functions <a href="#fde27240cfaf4479bc31ff50d3f619d0" title="permalink">#</a> </h3> <p> Perhaps you're happy with the above combinations, but can we do better? As an example, you'll notice that <code>to1337</code> only converts an upper-case <code>'E'</code> to <code>'3'</code>, but ignores a lower-case <code>'e'</code>. What if you also want the combination where <code>'e'</code> is first converted to upper case, and then to 1337? You'd like that, but you still want to retain the combinations where each of these transformations are applied without the other. </p> <p> Fear not; functions are values, so you can combine them as well! </p> <p> In the previous article, did you notice how you could model the presence or absence of a particular value? Specifically, the last character in the potential password could be <code>'!'</code>, but <code>'!'</code> could also be omitted. </p> <p> Consider, again, the expression for all password combinations: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;passwordCombinations&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;[<span style="color:navy;">sprintf</span>&nbsp;<span style="color:#a31515;">&quot;</span><span style="color:teal;">%s%s%s%s%s%s</span><span style="color:#a31515;">&quot;</span>] &nbsp;&nbsp;&nbsp;&nbsp;&lt;*&gt;&nbsp;[<span style="color:#a31515;">&quot;P&quot;</span>;&nbsp;<span style="color:#a31515;">&quot;p&quot;</span>]&nbsp;&lt;*&gt;&nbsp;[<span style="color:#a31515;">&quot;a&quot;</span>;&nbsp;<span style="color:#a31515;">&quot;4&quot;</span>]&nbsp;&lt;*&gt;&nbsp;[<span style="color:#a31515;">&quot;ssw&quot;</span>]&nbsp;&lt;*&gt;&nbsp;[<span style="color:#a31515;">&quot;o&quot;</span>;&nbsp;<span style="color:#a31515;">&quot;0&quot;</span>]&nbsp;&lt;*&gt;&nbsp;[<span style="color:#a31515;">&quot;rd&quot;</span>]&nbsp;&lt;*&gt;&nbsp;[<span style="color:#a31515;">&quot;&quot;</span>;&nbsp;<span style="color:#a31515;">&quot;!&quot;</span>]</pre> </p> <p> Notice that the last list contains two options: <code>"!"</code> and the empty string (<code>""</code>). You can read about this in <a href="http://blog.ploeh.dk/2017/10/06/monoids">another article series</a>, but <a href="http://blog.ploeh.dk/2017/10/10/strings-lists-and-sequences-as-a-monoid">character strings are monoids</a>, and one of the characteristics of monoids is that they have an <em>identity</em> element - a 'neutral' element, if you will. For strings, it's <code>""</code>; you can append or prepend the empty string as much as you'd like, but it's not going to change the other string. </p> <p> If you have a set of <a href="http://blog.ploeh.dk/2017/11/13/endomorphism-monoid">functions of the type <code>'a -&gt; 'a</code>, then the built-in function <code>id</code> is the identity element</a>. You can compose any <code>'a -&gt; 'a</code> function with <code>id</code>, and it's not going to change the other function. </p> <p> Since functions are values, then, you can create <em>combinations of functions:</em> </p> <p> <pre><span style="color:green;">//&nbsp;(char&nbsp;-&gt;&nbsp;char)&nbsp;list</span> <span style="color:blue;">let</span>&nbsp;maps&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;[<span style="color:blue;">fun</span>&nbsp;<span style="color:navy;">f</span>&nbsp;<span style="color:navy;">g</span>&nbsp;<span style="color:navy;">h</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:navy;">f</span>&nbsp;&gt;&gt;&nbsp;<span style="color:navy;">g</span>&nbsp;&gt;&gt;&nbsp;<span style="color:navy;">h</span>] &nbsp;&nbsp;&nbsp;&nbsp;&lt;*&gt;&nbsp;[<span style="color:teal;">Char</span>.<span style="color:navy;">toUpper</span>;&nbsp;<span style="color:navy;">id</span>] &nbsp;&nbsp;&nbsp;&nbsp;&lt;*&gt;&nbsp;[<span style="color:teal;">Char</span>.<span style="color:navy;">toLower</span>;&nbsp;<span style="color:navy;">id</span>] &nbsp;&nbsp;&nbsp;&nbsp;&lt;*&gt;&nbsp;[<span style="color:teal;">Char</span>.<span style="color:navy;">to1337</span>;&nbsp;<span style="color:navy;">id</span>]</pre> </p> <p> Here, <code>maps</code> is a list of functions, but it's not only three functions as in the above example. It's <em>eight</em> functions: </p> <p> <pre>&gt; List.length maps;; val it : int = 8</pre> </p> <p> The above applicative composition of <code>maps</code> combines three lists of functions. Each list presents two alternatives: a function (e.g. <code>Char.toUpper</code>), and <code>id</code>. In other words, a choice between doing something, and doing nothing. The lambda expression <code>fun f g h -&gt; f &gt;&gt; g &gt;&gt; h</code> takes three (curried) arguments, and returns the composition of calling <code>f</code>, then passing the result of that to <code>g</code>, and again passing the result of that to <code>h</code>. <code>f</code> is either <code>Char.toUpper</code> or <code>id</code>, <code>g</code> is either <code>Char.toLower</code> or <code>id</code>, and <code>h</code> is either <code>Char.to1337</code> or <code>id</code>. That's eight possible combinations. </p> <p> Combine eight functions with two <code>string</code> values, and you get sixteen alternatives back: </p> <p> <pre>&gt; List.map String.map maps &lt;*&gt; ["Hello"; "World"];; val it : string list = ["he110"; "w0r1d"; "hello"; "world"; "#3LL0"; "W0RLD"; "HELLO"; "WORLD"; "he110"; "w0r1d"; "hello"; "world"; "#e110"; "W0r1d"; "Hello"; "World"]</pre> </p> <p> Notice, for example, how one of the suggested alternatives is <code>"#3LL0"</code>. Previously, there was no translation from <code>'e'</code> to <code>'3'</code>, but now there is, via <code>Char.toUpper &gt;&gt; id &gt;&gt; Char.to1337</code>. </p> <p> Some of the combinations are redundant. For example, <code>"hello"</code> is generated twice, by <code>Char.toUpper &gt;&gt; Char.toLower &gt;&gt; id</code> and <code>id &gt;&gt; Char.toLower &gt;&gt; id</code>, respectively. You can reduce the output with <code>List.distinct</code>: </p> <p> <pre>&gt; List.map String.map maps &lt;*&gt; ["Hello"; "World"] |&gt; List.distinct;; val it : string list = ["he110"; "w0r1d"; "hello"; "world"; "#3LL0"; "W0RLD"; "HELLO"; "WORLD"; "#e110"; "W0r1d"; "Hello"; "World"]</pre> </p> <p> You can write equivalent code in Haskell, but it's so similar to the F# code that there's no reason to show it. </p> <h3 id="2000ef3aa60148e597de68d16048745f"> Translation to C# <a href="#2000ef3aa60148e597de68d16048745f" title="permalink">#</a> </h3> <p> Using the <code>Apply</code> extension methods from the previous article, you can translate the above code to C#. </p> <p> While you can use the .NET Base Class Library's <code>Char.ToUpperInvariant</code> and <code>Char.ToLowerInvariant</code> methods as is, you'll need to supply a <code>to1337</code> function. You can write it as a named static method, but you can also write it as a delegate: </p> <p> <pre><span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">char</span>,&nbsp;<span style="color:blue;">char</span>&gt;&nbsp;to1337&nbsp;=&nbsp;c&nbsp;=&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">switch</span>&nbsp;(c) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">case</span>&nbsp;<span style="color:#a31515;">&#39;A&#39;</span>: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">case</span>&nbsp;<span style="color:#a31515;">&#39;a&#39;</span>: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#a31515;">&#39;4&#39;</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">case</span>&nbsp;<span style="color:#a31515;">&#39;b&#39;</span>: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#a31515;">&#39;6&#39;</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">case</span>&nbsp;<span style="color:#a31515;">&#39;E&#39;</span>: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#a31515;">&#39;3&#39;</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">case</span>&nbsp;<span style="color:#a31515;">&#39;H&#39;</span>: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#a31515;">&#39;#&#39;</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">case</span>&nbsp;<span style="color:#a31515;">&#39;i&#39;</span>: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#a31515;">&#39;!&#39;</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">case</span>&nbsp;<span style="color:#a31515;">&#39;l&#39;</span>: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#a31515;">&#39;1&#39;</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">case</span>&nbsp;<span style="color:#a31515;">&#39;o&#39;</span>: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">case</span>&nbsp;<span style="color:#a31515;">&#39;O&#39;</span>: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#a31515;">&#39;0&#39;</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">case</span>&nbsp;<span style="color:#a31515;">&#39;t&#39;</span>: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#a31515;">&#39;+&#39;</span>; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">default</span>: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;c; &nbsp;&nbsp;&nbsp;&nbsp;} };</pre> </p> <p> You're also going to need an <code>id</code> function: </p> <p> <pre><span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">char</span>,&nbsp;<span style="color:blue;">char</span>&gt;&nbsp;id&nbsp;=&nbsp;c&nbsp;=&gt;&nbsp;c; </pre> </p> <p> In order to compose three functions to one, you can write something like this: </p> <p> <pre><span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">char</span>,&nbsp;<span style="color:blue;">char</span>&gt;,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">char</span>,&nbsp;<span style="color:blue;">char</span>&gt;,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">char</span>,&nbsp;<span style="color:blue;">char</span>&gt;,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">char</span>,&nbsp;<span style="color:blue;">char</span>&gt;&gt; &nbsp;&nbsp;&nbsp;&nbsp;compose3&nbsp;=&nbsp;(f,&nbsp;g,&nbsp;h)&nbsp;=&gt;&nbsp;x&nbsp;=&gt;&nbsp;h(g(f(x)));</pre> </p> <p> That's going to be a contender for some of the most obscure C# code I've written in a while. By the double use of <code>=&gt;</code>, you can tell that it's a delegate that returns a delegate. That's not even the worst part: check out the type of the thing! In reality, nothing happens here that doesn't also happen in the above F# code, but it's an example of the superiority of <a href="https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system">Hindley–Milner type inference</a>: in F#, you don't have to explicitly type out the type. </p> <p> With a function to compose three other functions, you can now apply the three alternative functions: </p> <p> <pre><span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">char</span>,&nbsp;<span style="color:blue;">char</span>&gt;&gt;&nbsp;maps&nbsp;=&nbsp;<span style="color:blue;">new</span>[]&nbsp;{&nbsp;compose3&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#2b91af;">Char</span>.ToUpperInvariant,&nbsp;id&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#2b91af;">Char</span>.ToLowerInvariant,&nbsp;id&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;to1337,&nbsp;id&nbsp;});</pre> </p> <p> Now you have a sequence of functions that translate <code>char</code> values to <code>char</code> values. What you really need, though, is a sequence of functions that translate <code>string</code> values to <code>string</code> values. </p> <p> The F# core library defines the built-in <code>String.map</code> function, but as far as I can tell, there's no equivalent method in the .NET Base Class Library. Therefore, you must implement it yourself: </p> <p> <pre><span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">char</span>,&nbsp;<span style="color:blue;">char</span>&gt;,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;&gt;&nbsp;stringMap&nbsp;=&nbsp;f&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;(<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.Select(f).ToArray());</pre> </p> <p> This is a function that takes a <code>Func&lt;char, char&gt;</code> as input and returns a <code>Func&lt;string, string&gt;</code>. Again, the type declaration isn't the prettiest. </p> <p> You can now apply <code>maps</code> to some <code>string</code> values, using the <code>Apply</code> extension method: </p> <p> <pre><span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;hellos&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;maps.Select(stringMap).Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;Hello&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;World&quot;</span>&nbsp;});</pre> </p> <p> This produces exactly the same output as the above F# example, even in the same order. </p> <p> Applicative functors are elegant in F# and Haskell, but awkward in a language like C# - mostly because of its inferior type inference engine. </p> <h3 id="001d02c7aa40400391b899f723ef9baa"> Summary <a href="#001d02c7aa40400391b899f723ef9baa" title="permalink">#</a> </h3> <p> Previous articles demonstrated how applicative lists can be used to compose several lists into a list that contains all possible combinations. In this article you saw how this also extends to combinations of functions. </p> <p> The last three articles (including the present) focus on lists as applicative functors, but lists aren't the only type of applicative functor. In the next articles, you'll encounter some other applicative functors. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/10/29/the-maybe-applicative-functor">The Maybe applicative 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>. An applicative password list http://blog.ploeh.dk/2018/10/15/an-applicative-password-list 2018-10-15T05:54:00+00:00 Mark Seemann <div id="post"> <p> <em>How to use the applicative functor capabilities of lists to create a password list, with examples that object-oriented programmers can understand.</em> </p> <p> This article is an instalment in <a href="http://blog.ploeh.dk/2018/10/01/applicative-functors">an article series about applicative functors</a>. In the <a href="http://blog.ploeh.dk/2018/10/08/full-deck">previous article</a>, you saw how to use <a href="https://www.haskell.org">Haskell</a> and <a href="https://fsharp.org">F#</a> lists as applicative functors to generate combinations of values. In this article, you'll see a similar example, but this time, there will also be a C# example. </p> <h3 id="ab0acd0982a64569a68ba92b041739a9"> Guess the password variation <a href="#ab0acd0982a64569a68ba92b041739a9" title="permalink">#</a> </h3> <p> Years ago, I worked in an organisation that (among other things) produced much demo software. Often, the demo software would include a demonstration of the security features of a product, which meant that, as a user evaluating the software, you had to log in with a user name and password. In order to keep things simple, the password was usually <em>Passw0rd!</em>, or some variation thereof. </p> <p> (Keep in mind that this was demoware. Password strength wasn't a concern. We explicitly wanted the password to be easy to guess, so that users evaluating the software had a chance to test how log in worked. This was long before social login and the like.) </p> <p> We had more than one package of demoware, and over the years, variations of the standard password had snuck in. Sometimes it'd be all lower-case; sometimes it'd use <em>4</em> instead of <em>a</em>, and so on. As the years went on, the number of possible permutations grew. </p> <p> Recently, I had a similar problem, but for security reasons, I don't want to divulge what it was. Let's just pretend that I had to guess one of those old demo passwords. </p> <p> There weren't <em>that</em> many possible variations, but just enough that I couldn't keep them systematically in my head. <ul> <li>The first letter could be upper or lower case.</li> <li>The second letter could be <em>a</em> or <em>4</em>.</li> <li>The <em>o</em> could be replaced with a zero (<em>0</em>).</li> <li>The password could end with an exclamation mark (<em>!</em>), but it might also be omitted.</li> </ul> Having recently discovered the power of lists as applicative functors, I started F# Interactive (FSI), and wrote the following: </p> <p> <pre>&gt; let (&lt;*&gt;) fs l = fs |&gt; List.collect (fun f -&gt; l |&gt; List.map f);; val ( &lt;*&gt; ) : fs:('a -&gt; 'b) list -&gt; l:'a list -&gt; 'b list &gt; [sprintf "%s%s%s%s%s%s"] &lt;*&gt; ["P"; "p"] &lt;*&gt; ["a"; "4"] &lt;*&gt; ["ssw"] &lt;*&gt; ["o"; "0"] &lt;*&gt; ["rd"] &lt;*&gt; [""; "!"];; val it : string list = ["Password"; "Password!"; "Passw0rd"; "Passw0rd!"; "P4ssword"; "P4ssword!"; "P4ssw0rd"; "P4ssw0rd!"; "password"; "password!"; "passw0rd"; "passw0rd!"; "p4ssword"; "p4ssword!"; "p4ssw0rd"; "p4ssw0rd!"]</pre> </p> <p> This produces a list of all the possible password combinations according to the above rules. Since there weren't that many, I could start trying each from the start, until I found the correct variation. </p> <p> The first list contains a single function. Due to the way <code>sprintf</code> works, <code>sprintf "%s%s%s%s%s%s"</code> is a function that takes six (curried) <code>string</code> arguments, and returns a <code>string</code>. The number 6 is no coincidence, because you'll notice that the <code>&lt;*&gt;</code> operator is used six times. </p> <p> There's no reason to repeat the exegesis from the previous article, but briefly: <ol> <li><code>sprintf "%s%s%s%s%s%s"</code> has the type <code>string -&gt; string -&gt; string -&gt; string -&gt; string -&gt; string -&gt; string</code>.</li> <li><code>[sprintf "%s%s%s%s%s%s"]</code> has the type <code>(string -&gt; string -&gt; string -&gt; string -&gt; string -&gt; string -&gt; string) list</code>.</li> <li><code>[sprintf "%s%s%s%s%s%s"] &lt;*&gt; ["P"; "p"]</code> has the type <code>(string -&gt; string -&gt; string -&gt; string -&gt; string -&gt; string) list</code>.</li> <li><code>[sprintf "%s%s%s%s%s%s"] &lt;*&gt; ["P"; "p"] &lt;*&gt; ["a"; "4"]</code> has the type <code>(string -&gt; string -&gt; string -&gt; string -&gt; string) list</code>.</li> <li>...and so on.</li> </ol> Notice that every time you add another list with <code>&lt;*&gt;</code>, an argument is removed from the resulting function contained in the returned list. When you've applied six lists with the <code>&lt;*&gt;</code> operator, the return value is no longer a list of functions, but a list of values. </p> <p> Clearly, then, that's no coincidence. I deliberately shaped the initial function to take six arguments, so that it would match the six segments I wanted to model. </p> <p> Perhaps the most interesting quality of applicative functors is that you can compose an arbitrary number of objects, as long as you have a function to match the number of arguments. </p> <h3 id="25e1617d768a4705a9756f230ddd9b39"> Haskell <a href="#25e1617d768a4705a9756f230ddd9b39" title="permalink">#</a> </h3> <p> This time I started with F#, but in Haskell, <code>&lt;*&gt;</code> is a built-in operator, so obviously this also works there: </p> <p> <pre><span style="color:#600277;">passwordCombinations</span>&nbsp;::&nbsp;[String] passwordCombinations&nbsp;<span style="color:#666666;">=</span> &nbsp;&nbsp;[printf&nbsp;<span style="color:#a31515;">&quot;%s%s%s%s%s%s&quot;</span>] &nbsp;&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;[<span style="color:#a31515;">&quot;P&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;p&quot;</span>]&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;[<span style="color:#a31515;">&quot;a&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;4&quot;</span>]&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;[<span style="color:#a31515;">&quot;ssw&quot;</span>]&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;[<span style="color:#a31515;">&quot;o&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;0&quot;</span>]&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;[<span style="color:#a31515;">&quot;rd&quot;</span>]&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;[<span style="color:#a31515;">&quot;&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;!&quot;</span>]</pre> </p> <p> The output is the same as the above F# code. </p> <h3 id="9c3412586a58460c8280212a13351331"> C# <a href="#9c3412586a58460c8280212a13351331" title="permalink">#</a> </h3> <p> While you can translate the concept of lists as an applicative functor to C#, this is where you start testing the limits of the language; or perhaps I've simply forgotten too much C# to do it full justice. </p> <p> Instead of making linked lists an applicative functor, let's consider a type closer to the spirit of the C# language: <code>IEnumerable&lt;T&gt;</code>. The following code attempts to turn <code>IEnumerable&lt;T&gt;</code> into an applicative functor. </p> <p> Consider the above F# implementation of <code>&lt;*&gt;</code> (explained in the previous article). It uses <code>List.collect</code> to flatten what would otherwise had been a list of lists. <code>List.collect</code> has the type <code>('a -&gt; 'b list) -&gt; 'a list -&gt; 'b list</code>. The corresponding method for <code>IEnumerable&lt;T&gt;</code> already exists in the .NET Base Class Library; it's called <a href="https://msdn.microsoft.com/en-us/library/bb534336">SelectMany</a>. (Incidentally, this is also the monadic <em>bind</em> function, but this is <em>still</em> not a monad tutorial.) </p> <p> For an applicative functor, we need a method that takes a sequence of functions, and a sequence of values, and produces a sequence of return values. You can translate the above F# function to this C# extension method: </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:#2b91af;">TResult</span>&gt;&nbsp;Apply&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;">IEnumerable</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;selectors, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;source) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;selectors.SelectMany(source.Select); }</pre> </p> <p> That's a single line of code! That's not so bad. What's the problem? </p> <p> So far there's no problem. You can, for example, write code like this: </p> <p> <pre><span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;sl&nbsp;=&nbsp;s&nbsp;=&gt;&nbsp;s.Length; <span style="color:blue;">var</span>&nbsp;lengths&nbsp;=&nbsp;<span style="color:blue;">new</span>[]&nbsp;{&nbsp;sl&nbsp;}.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;bar&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;baz&quot;</span>&nbsp;});</pre> </p> <p> This will return a sequence of the numbers <code>3, 3, 3</code>. That seems, however, like quite a convoluted way of getting the lengths of some strings. A normal <code>Select</code> method would have sufficed. </p> <p> Is it possible to repeat the above password enumeration in C#? In order to do that, you need a function that takes six <code>string</code> arguments and returns a <code>string</code>: </p> <p> <pre><span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;concat&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;(x,&nbsp;y,&nbsp;z,&nbsp;æ,&nbsp;ø,&nbsp;å)&nbsp;=&gt;&nbsp;x&nbsp;+&nbsp;y&nbsp;+&nbsp;z&nbsp;+&nbsp;æ&nbsp;+&nbsp;ø&nbsp;+&nbsp;å;</pre> </p> <p> With programmers' penchant to start with the variable name <code>x</code>, and continue with <code>y</code> and <code>z</code>, most people will have a problem with six variables - but not us Danes! Fortunately, we've officially added three extra letters to our alphabet for this very purpose! So with that small problem out of the way, you can now attempt to reproduce the above F# code: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;combinations&nbsp;=&nbsp;<span style="color:blue;">new</span>[]&nbsp;{&nbsp;concat&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;P&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;p&quot;</span>&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;a&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;4&quot;</span>&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;ssw&quot;</span>&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;o&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;0&quot;</span>&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;rd&quot;</span>&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;!&quot;</span>&nbsp;});</pre> </p> <p> That looks promising, but there's one problem: <em>it doesn't compile</em>. </p> <p> The problem is that <code>concat</code> is a function that takes six arguments, and the above <code>Apply</code> method expects <code>selectors</code> to be functions that take exactly one argument. </p> <p> Alas, while it's not pretty, you can attempt to address the problem with an overload: </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:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">T3</span>,&nbsp;<span style="color:#2b91af;">T4</span>,&nbsp;<span style="color:#2b91af;">T5</span>,&nbsp;<span style="color:#2b91af;">T6</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;Apply&lt;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">T3</span>,&nbsp;<span style="color:#2b91af;">T4</span>,&nbsp;<span style="color:#2b91af;">T5</span>,&nbsp;<span style="color:#2b91af;">T6</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">T3</span>,&nbsp;<span style="color:#2b91af;">T4</span>,&nbsp;<span style="color:#2b91af;">T5</span>,&nbsp;<span style="color:#2b91af;">T6</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;selectors, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">T1</span>&gt;&nbsp;source) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;selectors.SelectMany(f&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;source.Select(x&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:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">T3</span>,&nbsp;<span style="color:#2b91af;">T4</span>,&nbsp;<span style="color:#2b91af;">T5</span>,&nbsp;<span style="color:#2b91af;">T6</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;g&nbsp;=&nbsp;(y,&nbsp;z,&nbsp;æ,&nbsp;ø,&nbsp;å)&nbsp;=&gt;&nbsp;f(x,&nbsp;y,&nbsp;z,&nbsp;æ,&nbsp;ø,&nbsp;å); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;g; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;})); }</pre> </p> <p> This overload of <code>Apply</code> takes <code>selectors</code> of arity six, and return a sequence of functions with arity five. </p> <p> Does it work now, then? </p> <p> Unfortunately, it still doesn't compile, because <code>new[] { concat }.Apply(new[] { "P", "p" })</code> has the type <code>IEnumerable&lt;Func&lt;string, string, string, string, string, string&gt;&gt;</code>, and no overload of <code>Apply</code> exists that supports <code>selectors</code> with arity five. </p> <p> You'll have to add such an overload as well: </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:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">T3</span>,&nbsp;<span style="color:#2b91af;">T4</span>,&nbsp;<span style="color:#2b91af;">T5</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;Apply&lt;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">T3</span>,&nbsp;<span style="color:#2b91af;">T4</span>,&nbsp;<span style="color:#2b91af;">T5</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">T3</span>,&nbsp;<span style="color:#2b91af;">T4</span>,&nbsp;<span style="color:#2b91af;">T5</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;selectors, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">T1</span>&gt;&nbsp;source) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;selectors.SelectMany(f&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;source.Select(x&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:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">T3</span>,&nbsp;<span style="color:#2b91af;">T4</span>,&nbsp;<span style="color:#2b91af;">T5</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;g&nbsp;=&nbsp;(y,&nbsp;z,&nbsp;æ,&nbsp;ø)&nbsp;=&gt;&nbsp;f(x,&nbsp;y,&nbsp;z,&nbsp;æ,&nbsp;ø); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;g; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;})); }</pre> </p> <p> You can probably see where this is going. This overload returns a sequence of functions with arity four, so you'll have to add an <code>Apply</code> overload for such functions as well, plus for functions with arity three and two. Once you've done that, the above <a href="https://martinfowler.com/bliki/FluentInterface.html">fluent</a> chain of <code>Apply</code> method calls work, and you get a sequence containing all the password variations. </p> <p> <pre>&gt; <span style="color:blue;">new</span>[]&nbsp;{&nbsp;concat&nbsp;} . .Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;P&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;p&quot;</span>&nbsp;}) . .Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;a&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;4&quot;</span>&nbsp;}) . .Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;ssw&quot;</span>&nbsp;}) . .Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;o&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;0&quot;</span>&nbsp;}) . .Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;rd&quot;</span>&nbsp;}) . .Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;!&quot;</span>&nbsp;}) string[16] { "Password", "Password!", "Passw0rd", "Passw0rd!", "P4ssword", "P4ssword!", "P4ssw0rd", "P4ssw0rd!", "password", "password!", "passw0rd", "passw0rd!", "p4ssword", "p4ssword!", "p4ssw0rd", "p4ssw0rd!" }</pre> </p> <p> In F# and Haskell, the compiler automatically figures out the return type of each application, due to a combination of currying and <a href="https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system">Hindley–Milner type inference</a>. Perhaps I've allowed my C# skills to atrophy, but I don't think there's an easy resolution to this problem in C#. </p> <p> Obviously, you can always write a reusable library with <code>Apply</code> overloads that support up to some absurd arity. Once those methods are written, they're unlikely to change. Still, it seems to me that we're pushing the envelope. </p> <h3 id="5f60025e198f42ecbba731a0869217ed"> Summary <a href="#5f60025e198f42ecbba731a0869217ed" title="permalink">#</a> </h3> <p> In this article, you saw how to turn C# sequences into an applicative functor. While possible, there are some bumps in the road. </p> <p> There's still an aspect of using lists and sequences as applicative functors that I've been deliberately ignoring so far. The next article covers that. After that, we'll take a break from lists and look at some other applicative functors. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/10/22/applicative-combinations-of-functions">Applicative combinations of functions</a>. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="0ded7ac93aad8ba7b1063dd49c2051f1"> <div class="comment-author">Tyson Williams</div> <div class="comment-content"> <blockquote> In F# and Haskell, the compiler automatically figures out the return type of each application, due to a combination of currying and Hindley–Milner type inference. Perhaps I've allowed my C# skills to atrophy, but I don't think there's an easy resolution to this problem in C#. </blockquote> <p> I think the difference is that all functions in F# and Haskell are automatically curried, but nothing is automatically curreid in C#. If you explicitly curry <code>concat</code>, then the code complies and works as expected. Here is one way to achieve that. </p> <p> <pre><span style="color:blue;">var</span>&nbsp;combinations&nbsp;=&nbsp;<span style="color:blue;">new</span>[]&nbsp;{&nbsp;LanguageExt.<span style="color:#2b91af;">Prelude</span>.curry(concat)&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;P&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;p&quot;</span>&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;a&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;4&quot;</span>&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;ssw&quot;</span>&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;o&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;0&quot;</span>&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;rd&quot;</span>&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;.Apply(<span style="color:blue;">new</span>[]&nbsp;{&nbsp;<span style="color:#a31515;">&quot;&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;!&quot;</span>&nbsp;});</pre> </p> <p> In this example, I curried <code>concat</code> using <a href="https://github.com/louthy/language-ext/blob/master/LanguageExt.Core/Prelude/Prelude_Curry.cs#L65"><code>curry</code></a> from the NuGet package <a href="https://github.com/louthy/language-ext">LanguageExt</a>. It is a base class library for functional programming in C#. </p> <p> So you don't need many overloads of your <code>Apply</code> for varrying numbers of type parameters. You just need many overloads of <code>curry</code>. </p> </div> <div class="comment-date">2018-10-18 01:45 UTC</div> </div> <div class="comment" id="b4e76681ea894aa3be1e6b836343c148"> <div class="comment-author"><a href="http://blog.ploeh.dk">Mark Seemann</a></div> <div class="comment-content"> <p> Tyson, thank you for writing. Yes, you're right that it's the lack of default currying that makes this sort of style less than ideal in C#. This seems to be clearly demonstrated by your example. </p> </div> <div class="comment-date">2018-10-30 7:43 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>. Full deck http://blog.ploeh.dk/2018/10/08/full-deck 2018-10-08T06:17:00+00:00 Mark Seemann <div id="post"> <p> <em>An introduction to applicative functors in Haskell, with a translation to F#.</em> </p> <p> This article is an instalment in <a href="http://blog.ploeh.dk/2018/10/01/applicative-functors">an article series about applicative functors</a>. While (non-applicative) <a href="http://blog.ploeh.dk/2018/03/22/functors">functors</a> can be translated to an object-oriented language like C# in a straightforward manner, applicative functors are more entrenched in functional languages like <a href="https://www.haskell.org">Haskell</a>. This article introduces the concept with a motivating example in Haskell, and also shows a translation to <a href="https://fsharp.org">F#</a>. In the next article, you'll also see how to implement an applicative functor in C#. </p> <h3 id="bdf22a40f9f04b6b9929f46dbafe7911"> Deck of cards in Haskell <a href="#bdf22a40f9f04b6b9929f46dbafe7911" title="permalink">#</a> </h3> <p> Imagine that you want to model a card game. In order to do so, you start by defining data types for suits, faces, and cards: </p> <p> <pre><span style="color:blue;">data</span>&nbsp;<span style="color:#dd0000;">Suit</span>&nbsp;<span style="color:#666666;">=</span> &nbsp;&nbsp;<span style="color:#dd0000;">Diamonds</span>&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Hearts</span>&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Clubs</span>&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Spades</span>&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;">Enum</span>,&nbsp;<span style="color:#a31515;">Bounded</span>) <span style="color:blue;">data</span>&nbsp;<span style="color:#dd0000;">Face</span>&nbsp;<span style="color:#666666;">=</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#dd0000;">Two</span>&nbsp;&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Three</span>&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Four</span>&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Five</span>&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Six</span>&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Seven</span>&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Eight</span>&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Nine</span>&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Ten</span> &nbsp;&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Jack</span>&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Queen</span>&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">King</span>&nbsp;<span style="color:#666666;">|</span>&nbsp;<span style="color:#dd0000;">Ace</span> &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;">Enum</span>,&nbsp;<span style="color:#a31515;">Bounded</span>) <span style="color:blue;">data</span>&nbsp;<span style="color:#dd0000;">Card</span>&nbsp;<span style="color:#666666;">=</span>&nbsp;<span style="color:#dd0000;">Card</span>&nbsp;{&nbsp;face&nbsp;<span style="color:#666666;">::</span>&nbsp;<span style="color:#dd0000;">Face</span>,&nbsp;suit&nbsp;<span style="color:#666666;">::</span>&nbsp;<span style="color:#dd0000;">Suit</span>&nbsp;}&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#a31515;">Show</span>,&nbsp;<span style="color:#a31515;">Eq</span>)</pre> </p> <p> Since both <code>Suit</code> and <code>Face</code> are instances of the <code>Enum</code> and <code>Bounded</code> typeclasses, you can easily enumerate them: </p> <p> <pre><span style="color:#600277;">allFaces</span>&nbsp;::&nbsp;[<span style="color:blue;">Face</span>] allFaces&nbsp;<span style="color:#666666;">=</span>&nbsp;[minBound&nbsp;<span style="color:#666666;">..</span>&nbsp;maxBound] <span style="color:#600277;">allSuits</span>&nbsp;::&nbsp;[<span style="color:blue;">Suit</span>] allSuits&nbsp;<span style="color:#666666;">=</span>&nbsp;[minBound&nbsp;<span style="color:#666666;">..</span>&nbsp;maxBound]</pre> </p> <p> For example, <code>allSuits</code> enumerates all four <code>Suit</code> values: </p> <p> <pre>λ&gt; allSuits [Diamonds,Hearts,Clubs,Spades]</pre> </p> <p> Notice, by the way, how the code for <code>allFaces</code> and <code>allSuits</code> is identical. The behaviour, however, is different, because the types are different. </p> <p> While you can enumerate suits and faces, <em>how do you create a full deck of cards?</em> </p> <p> A full deck of cards should contain one card of every possible combination of suit and face. Here's one way to do it, taking advantage of lists being applicative functors: </p> <p> <pre><span style="color:#600277;">fullDeck</span>&nbsp;::&nbsp;[<span style="color:blue;">Card</span>] fullDeck&nbsp;<span style="color:#666666;">=</span>&nbsp;pure&nbsp;<span style="color:#dd0000;">Card</span>&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;allFaces&nbsp;<span style="color:#666666;">&lt;*&gt;</span>&nbsp;allSuits</pre> </p> <p> This will give you all the possible cards. Here are the first six: </p> <p> <pre>λ&gt; forM_ (take 6 fullDeck) print Card {face = Two, suit = Diamonds} Card {face = Two, suit = Hearts} Card {face = Two, suit = Clubs} Card {face = Two, suit = Spades} Card {face = Three, suit = Diamonds} Card {face = Three, suit = Hearts}</pre> </p> <p> How does it work? Let's break it down, starting from left: </p> <p> <pre>λ&gt; :type Card Card :: Face -&gt; Suit -&gt; Card λ&gt; :type pure Card pure Card :: Applicative f =&gt; f (Face -&gt; Suit -&gt; Card) λ&gt; :type pure Card &lt;*&gt; allFaces pure Card &lt;*&gt; allFaces :: [Suit -&gt; Card] λ&gt; :type pure Card &lt;*&gt; allFaces &lt;*&gt; allSuits pure Card &lt;*&gt; allFaces &lt;*&gt; allSuits :: [Card]</pre> </p> <p> From the top, <code>Card</code> is a function that takes a <code>Face</code> value and a <code>Suit</code> value and returns a <code>Card</code> value. Object-oriented programmers can think of it as a constructor. </p> <p> Next, <code>pure Card</code> is the <code>Card</code> function, elevated to an applicative functor. At this point, the compiler hasn't decided which particular applicative functor it is; it could be any applicative functor. Specifically, it turns out to be the list type (<code>[]</code>), which means that <code>pure Card</code> has the type <code>[Face -&gt; Suit -&gt; Card]</code>. That is: it's a list of functions, but a list of only a single function. At this point, however, this is still premature. The type doesn't materialise until we apply the second expression. </p> <p> The type of <code>allFaces</code> is clearly <code>[Face]</code>. Since the <code>&lt;*&gt;</code> operator has the type <code>Applicative f =&gt; f (a -&gt; b) -&gt; f a -&gt; f b</code>, the expression on the left must be the same functor as the expression on the right. The list type (<code>[]</code>) is an applicative functor, and because <code>allFaces</code> is a list, then <code>pure Card</code> must also be a list, in the expression <code>pure Card &lt;*&gt; allFaces</code>. In other words, in the definition of <code>&lt;*&gt;</code>, you can substitute <code>f</code> with <code>[]</code>, and <code>a</code> with <code>Face</code>. The interim result is <code>[Face -&gt; b] -&gt; [Face] -&gt; [b]</code>. What is <code>b</code>, then? </p> <p> You already know that <code>pure Card</code> has the type <code>[Face -&gt; Suit -&gt; Card]</code>, so <code>b</code> must be <code>Suit -&gt; Card</code>. That's the reason that <code>pure Card &lt;*&gt; allFaces</code> has the type <code>[Suit -&gt; Card]</code>. It's a list of functions. This means that you can use <code>&lt;*&gt;</code> a second time, this time with <code>allSuits</code>, which has the type <code>[Suit]</code>. </p> <p> Using the same line of reasoning as before, you can substitute <code>Suit</code> for <code>a</code> in the type of <code>&lt;*&gt;</code>, and you get <code>[Suit -&gt; b] -&gt; [Suit] -&gt; [b]</code>. What is <code>b</code> now? From the previous step, you know that the the expression on the left has the type <code>[Suit -&gt; Card]</code>, so <code>b</code> must be <code>Card</code>. That's why the entire expression has the type <code>[Card]</code>. </p> <h3 id="570f38cdb46b420e904fb656faa662ff"> Deck of cards in F# <a href="#570f38cdb46b420e904fb656faa662ff" title="permalink">#</a> </h3> <p> You can translate the above Haskell code to F#. The first step is to make F# lists applicative. F# also supports custom operators, so you can add a function called <code>&lt;*&gt;</code>: </p> <p> <pre><span style="color:green;">//&nbsp;(&#39;a&nbsp;-&gt;&nbsp;&#39;b)&nbsp;list&nbsp;-&gt;&nbsp;&#39;a&nbsp;list&nbsp;-&gt;&nbsp;&#39;b&nbsp;list</span> <span style="color:blue;">let</span>&nbsp;(&lt;*&gt;)&nbsp;fs&nbsp;l&nbsp;=&nbsp;fs&nbsp;|&gt;&nbsp;<span style="color:teal;">List</span>.<span style="color:navy;">collect</span>&nbsp;(<span style="color:blue;">fun</span>&nbsp;<span style="color:navy;">f</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;l&nbsp;|&gt;&nbsp;<span style="color:teal;">List</span>.<span style="color:navy;">map</span>&nbsp;<span style="color:navy;">f</span>)</pre> </p> <p> This implementation iterates over all the functions in <code>fs</code>; for each function, it maps the list <code>l</code> with that function. Had you done that with a normal <code>List.map</code>, this would have returned a list of lists, but by using <code>List.collect</code>, you flatten the list. </p> <p> It's worth noting that this isn't the only way you could have implemented <code>&lt;*&gt;</code>, but this is the implementation that behaves like the Haskell function. An alternative implementation could have been this: </p> <p> <pre><span style="color:green;">//&nbsp;(&#39;a&nbsp;-&gt;&nbsp;&#39;b)&nbsp;list&nbsp;-&gt;&nbsp;&#39;a&nbsp;list&nbsp;-&gt;&nbsp;&#39;b&nbsp;list</span> <span style="color:blue;">let</span>&nbsp;(&lt;*&gt;)&nbsp;fs&nbsp;=&nbsp;<span style="color:teal;">List</span>.<span style="color:navy;">collect</span>&nbsp;(<span style="color:blue;">fun</span>&nbsp;x&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;fs&nbsp;|&gt;&nbsp;<span style="color:teal;">List</span>.<span style="color:navy;">map</span>&nbsp;(<span style="color:blue;">fun</span>&nbsp;<span style="color:navy;">f</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:navy;">f</span>&nbsp;x))</pre> </p> <p> This variation has the same type as the first example, and still returns all combinations, but the order is different. In the following of this article, as well as in subsequent articles, I'll use the first version. </p> <p> Here's the playing cards example translated to F#: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;<span style="color:teal;">Suit</span>&nbsp;=&nbsp;<span style="color:navy;">Diamonds</span>&nbsp;|&nbsp;<span style="color:navy;">Hearts</span>&nbsp;|&nbsp;<span style="color:navy;">Clubs</span>&nbsp;|&nbsp;<span style="color:navy;">Spades</span> <span style="color:blue;">type</span>&nbsp;<span style="color:teal;">Face</span>&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;<span style="color:navy;">Two</span>&nbsp;|&nbsp;<span style="color:navy;">Three</span>&nbsp;|&nbsp;<span style="color:navy;">Four</span>&nbsp;|&nbsp;<span style="color:navy;">Five</span>&nbsp;|&nbsp;<span style="color:navy;">Six</span>&nbsp;|&nbsp;<span style="color:navy;">Seven</span>&nbsp;|&nbsp;<span style="color:navy;">Eight</span>&nbsp;|&nbsp;<span style="color:navy;">Nine</span>&nbsp;|&nbsp;<span style="color:navy;">Ten</span> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:navy;">Jack</span>&nbsp;|&nbsp;<span style="color:navy;">Queen</span>&nbsp;|&nbsp;<span style="color:navy;">King</span>&nbsp;|&nbsp;<span style="color:navy;">Ace</span> <span style="color:blue;">type</span>&nbsp;<span style="color:teal;">Card</span>&nbsp;=&nbsp;{&nbsp;Face:&nbsp;<span style="color:teal;">Face</span>;&nbsp;Suit&nbsp;:&nbsp;<span style="color:teal;">Suit</span>&nbsp;} <span style="color:green;">//&nbsp;Face&nbsp;list</span> <span style="color:blue;">let</span>&nbsp;allFaces&nbsp;=&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:navy;">Two</span>;&nbsp;<span style="color:navy;">Three</span>;&nbsp;<span style="color:navy;">Four</span>;&nbsp;<span style="color:navy;">Five</span>;&nbsp;<span style="color:navy;">Six</span>;&nbsp;<span style="color:navy;">Seven</span>;&nbsp;<span style="color:navy;">Eight</span>;&nbsp;<span style="color:navy;">Nine</span>;&nbsp;<span style="color:navy;">Ten</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:navy;">Jack</span>;&nbsp;<span style="color:navy;">Queen</span>;&nbsp;<span style="color:navy;">King</span>;&nbsp;<span style="color:navy;">Ace</span>] <span style="color:green;">//&nbsp;Suit&nbsp;list</span> <span style="color:blue;">let</span>&nbsp;allSuits&nbsp;=&nbsp;[<span style="color:navy;">Diamonds</span>;&nbsp;<span style="color:navy;">Hearts</span>;&nbsp;<span style="color:navy;">Clubs</span>;&nbsp;<span style="color:navy;">Spades</span>] <span style="color:green;">//&nbsp;Card&nbsp;list</span> <span style="color:blue;">let</span>&nbsp;fullDeck&nbsp;=&nbsp;[<span style="color:blue;">fun</span>&nbsp;f&nbsp;s&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;{&nbsp;Face&nbsp;=&nbsp;f;&nbsp;Suit&nbsp;=&nbsp;s&nbsp;}]&nbsp;&lt;*&gt;&nbsp;allFaces&nbsp;&lt;*&gt;&nbsp;allSuits</pre> </p> <p> The F# code is slightly more verbose than the Haskell code, because you have to repeat all the cases for <code>Suit</code> and <code>Face</code>. You can't enumerate them automatically, like you can in Haskell. </p> <p> It didn't make much sense to me to attempt to define a <code>pure</code> function, so instead I simply inserted a single lambda expression in a list, using the normal square-bracket syntax. F# doesn't have constructors for record types, so you have to pass a lambda expression, whereas in Haskell, you could simply use the <code>Card</code> function. </p> <p> The result is the same, though: </p> <p> <pre>&gt; fullDeck |&gt; List.take 6 |&gt; List.iter (printfn "%A");; {Face = Two; Suit = Diamonds;} {Face = Two; Suit = Hearts;} {Face = Two; Suit = Clubs;} {Face = Two; Suit = Spades;} {Face = Three; Suit = Diamonds;} {Face = Three; Suit = Hearts;}</pre> </p> <p> While the mechanics of applicative functors translate well to F#, it leaves you with at least one problem. If you add the above operator <code>&lt;*&gt;</code>, you've now 'used up' that operator for lists. While you <em>can</em> define an operator of the same name for e.g. <code>option</code>, you'd have to put them in separate modules or namespaces in order to prevent them from colliding. This also means that you can't easily use them together. </p> <p> For that reason, I wouldn't consider this the most <a href="http://blog.ploeh.dk/2015/08/03/idiomatic-or-idiosyncratic">idiomatic</a> way to create a full deck of cards in F#. Normally, I'd do this instead: </p> <p> <pre><span style="color:green;">//&nbsp;Card&nbsp;list</span> <span style="color:blue;">let</span>&nbsp;fullDeck&nbsp;=&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">for</span>&nbsp;suit&nbsp;<span style="color:blue;">in</span>&nbsp;allSuits&nbsp;<span style="color:blue;">do</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">for</span>&nbsp;face&nbsp;<span style="color:blue;">in</span>&nbsp;allFaces&nbsp;<span style="color:blue;">do</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">yield</span>&nbsp;{&nbsp;Face&nbsp;=&nbsp;face;&nbsp;Suit&nbsp;=&nbsp;suit&nbsp;}&nbsp;]</pre> </p> <p> This alternative syntax takes advantage of F#'s 'extended list comprehension' syntax. FWIW, you could have done something similar in Haskell: </p> <p> <pre><span style="color:#600277;">fullDeck</span>&nbsp;::&nbsp;[<span style="color:blue;">Card</span>] fullDeck&nbsp;<span style="color:#666666;">=</span>&nbsp;[<span style="color:#dd0000;">Card</span>&nbsp;f&nbsp;s&nbsp;<span style="color:#666666;">|</span>&nbsp;f&nbsp;<span style="color:#666666;">&lt;-</span>&nbsp;allFaces,&nbsp;s&nbsp;<span style="color:#666666;">&lt;-</span>&nbsp;allSuits]</pre> </p> <p> List comprehension, however, is (as the name implies) specific to lists, whereas an <em>applicative functor</em> is a more general concept. </p> <h3 id="cef0030207354d1fbf0ab2c1a791eb84"> Summary <a href="#cef0030207354d1fbf0ab2c1a791eb84" title="permalink">#</a> </h3> <p> This article introduced you to lists as an applicative functor, using the motivating example of having to populate a full deck of cards with all possible combinations of suits and faces. </p> <p> The next article in the series shows another list example. The F# and Haskell code will be similar to the code in the present article, but the next article will also include a translation to C#. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/10/15/an-applicative-password-list">An applicative password list</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>. Applicative functors http://blog.ploeh.dk/2018/10/01/applicative-functors 2018-10-01T06:34:00+00:00 Mark Seemann <div id="post"> <p> <em>An applicative functor is a useful abstraction. While typically associated with functional programming, applicative functors can be conjured into existence 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> In a <a href="http://blog.ploeh.dk/2018/03/22/functors">former article series</a>, you learned about functors, and how they also exist in object-oriented design. Perhaps the utility of this still eludes you, although, if you've ever had experience with LINQ in C#, you should realise that the abstraction is invaluable. Functors are abundant; <em>applicative functors</em> not quite so much. On the other hand, applicative functors enable you to <em>do</em> more. </p> <p> I find it helpful to think of applicative functors as an abstraction that enable you to express <em>combinations</em> of things. </p> <p> In the functor article series, I mostly focused on the mechanics of implementation. In this article series, I think that you'll find it helpful to slightly change the perspective. In these articles, I'll show you various motivating examples of how applicative functors are useful. <ul> <li><a href="http://blog.ploeh.dk/2018/10/08/full-deck">Full deck</a></li> <li><a href="http://blog.ploeh.dk/2018/10/15/an-applicative-password-list">An applicative password list</a></li> <li><a href="http://blog.ploeh.dk/2018/10/22/applicative-combinations-of-functions">Applicative combinations of functions</a></li> <li><a href="http://blog.ploeh.dk/2018/10/29/the-maybe-applicative-functor">The Maybe applicative functor</a></li> <li><a href="http://blog.ploeh.dk/2018/11/05/applicative-validation">Applicative validation</a></li> <li>Test Data Generator</li> <li>Danish CPR numbers in F#</li> </ul> You should consider reading one or more of these articles before continuing the present article. </p> <h3 id="6173a96aedaa4e97ad868c159e6d06fa"> A Haskell perspective <a href="#6173a96aedaa4e97ad868c159e6d06fa" title="permalink">#</a> </h3> <p> A normal functor maps objects in an 'elevated world' (like C#'s <code>IEnumerable&lt;T&gt;</code> or <code>IObservable&lt;T&gt;</code>) using a function in the 'normal world'. As a variation, an applicative functor maps objects in an 'elevated world' using functions from the same 'elevated world'. </p> <p> In <a href="https://haskell.org">Haskell</a>, an applicative functor is defined <em>like</em> this: </p> <p> <pre><span style="color:blue;">class</span>&nbsp;Functor&nbsp;f&nbsp;=&gt;&nbsp;<span style="color:#a31515;">Applicative</span>&nbsp;f&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;<span style="color:#600277;">pure</span>&nbsp;&nbsp;::&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;f&nbsp;a &nbsp;&nbsp;(&lt;*<span style="color:blue;">&gt;</span>)&nbsp;::&nbsp;f&nbsp;(a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;b)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;f&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;f&nbsp;b </pre> </p> <p> This is a <strong>simplification</strong>; there's more to the <code>Applicative</code> typeclass than this, but this should highlight the essence. What it says is that an applicative functor must already be a <code>Functor</code>. It could be any sort of <code>Functor</code>, like <code>[]</code> (linked list), <code>Maybe</code>, <code>Either</code>, and so on. Since <code>Functor</code> is an abstraction, it's called <code>f</code>. </p> <p> The definition furthermore says that in order for a functor to be applicative, two functions must exist: <code>pure</code> and <code>&lt;*&gt;</code> (<em>'apply'</em>). </p> <p> <code>pure</code> is easy to understand. It simply 'elevates' a 'normal' value to a functor value. For example, you can elevate the number <code>42</code> to a list value by putting it in a list with a single element: <code>[42]</code>. Or you can elevate <code>"foo"</code> to <code>Maybe</code> by containing it in the <code>Just</code> case: <code>Just "foo"</code>. That is, literally, what <code>pure</code> does for <code>[]</code> (list) and <code>Maybe</code>. </p> <p> The <code>&lt;*&gt;</code> operator applies an 'elevated' function to an 'elevated' value. When <code>f</code> is <code>[]</code>, this literally means that you have a list of functions that you have to apply to a list of values. Perhaps you can already see what I meant by <em>combinations</em> of things. </p> <p> This sounds abstract, but follow the above list of links in order to see several examples. </p> <h3 id="6f9b2f13951e475d8c4fc9682ad96a94"> An F# perspective <a href="#6f9b2f13951e475d8c4fc9682ad96a94" title="permalink">#</a> </h3> <p> Applicative functors aren't explicitly modelled in <a href="https://fsharp.org">F#</a>, but they're easy enough to add if you need them. F# doesn't have typeclasses, so implementing applicative functors tend to be more on a case-by-case basis. </p> <p> If you need <code>list</code> to be applicative, <code>pure</code> should have the type <code>'a -&gt; 'a list</code>, and <code>&lt;*&gt;</code> should have the type <code>('a -&gt; 'b) list -&gt; 'a list -&gt; 'b list</code>. At this point, you already run into the problem that <code>pure</code> is a reserved keyword in F#, so you'll have to find another name, or simply ignore that function. </p> <p> If you need <code>option</code> to be applicative, <code>&lt;*&gt;</code> should have the type <code>('a -&gt; 'b) option -&gt; 'a option -&gt; 'b option</code>. Now you run into your second problem, because which function is <code>&lt;*&gt;</code>? The one for <code>list</code>, or the one for <code>option</code>? It can't be both, so you'll have to resort to all sorts of hygiene to prevent these two versions of the same operator from clashing. This somewhat limits its usefulness. </p> <p> Again, refer to the above list of linked articles for concrete examples. </p> <h3 id="cef395ee19644f30bfd1ad7a84b6f912"> A C# perspective <a href="#cef395ee19644f30bfd1ad7a84b6f912" title="permalink">#</a> </h3> <p> Applicative functors push the limits of what you can express in C#, but the equivalent to <code>&lt;*&gt;</code> would be a method with this signature: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Functor</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;Apply&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;">Functor</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;selector, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Functor</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;source)</pre> </p> <p> Here, the class <code>Functor&lt;T&gt;</code> is a place-holder for a proper functor class. A concrete example could be for <code>IEnumerable&lt;T&gt;</code>: </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:#2b91af;">TResult</span>&gt;&nbsp;Apply&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;">IEnumerable</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;&nbsp;selectors, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;source)</pre> </p> <p> As you can see, here you somehow have to figure out how to combine a sequence of functions with a sequence of values. </p> <p> In some of the examples in the above list of linked articles, you'll see how this will stretch the capability of C#. </p> <h3 id="ffa16273a2a0428f90190f8d559cf0a6"> Summary <a href="#ffa16273a2a0428f90190f8d559cf0a6" title="permalink">#</a> </h3> <p> This article only attempts to provide an overview of applicative functors, while examples are given in linked articles. I find it helpful to think of applicative functors as an abstraction that enables you to model arbitrary <em>combinations</em> of objects. This is a core feature in Haskell, occasionally useful in F#, and somewhat alien to C#. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/10/08/full-deck">Full deck</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>. Asynchronous functors http://blog.ploeh.dk/2018/09/24/asynchronous-functors 2018-09-24T03:37:00+00:00 Mark Seemann <div id="post"> <p> <em>Asynchronous computations form functors. 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>. The previous article covered the <a href="http://blog.ploeh.dk/2018/09/10/the-lazy-functor">Lazy functor</a>. In this article, you'll learn about closely related functors: .NET Tasks and <a href="https://fsharp.org">F#</a> <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/asynchronous-workflows">asynchronous workflows</a>. </p> <p> A word of warning is in order. .NET Tasks aren't <a href="https://en.wikipedia.org/wiki/Referential_transparency">referentially transparent</a>, whereas F# asynchronous computations are. You could argue, then, that .NET Tasks aren't proper functors, but you mostly observe the difference when you perform impure operations. As a general observation, when impure operations are allowed, the conclusions of <a href="http://blog.ploeh.dk/2017/10/04/from-design-patterns-to-category-theory">this overall article series</a> are precarious. We can't radically change how the .NET languages work, so we'll have to soldier on, pretending that impure operations are delegated to other parts of our system. Under this undue assumption, we can pretend that <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1">Task&lt;T&gt;</a> forms a functor. </p> <h3 id="f82479d93d5d40ed83749a6d9fc309dc"> Task functor <a href="#f82479d93d5d40ed83749a6d9fc309dc" title="permalink">#</a> </h3> <p> You can write an idiomatic <code>Select</code> extension method for <code>Task&lt;T&gt;</code> like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">async</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Task</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;">Task</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;">var</span>&nbsp;x&nbsp;=&nbsp;<span style="color:blue;">await</span>&nbsp;source; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;selector(x); }</pre> </p> <p> With this extension method in scope, you can compose asynchronous computations like this: </p> <p> <pre><span style="color:#2b91af;">Task</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;x&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Task</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, if you prefer <em>query syntax:</em> </p> <p> <pre><span style="color:#2b91af;">Task</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;x&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Task</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> In both cases, you start with a <code>Task&lt;int&gt;</code> which you map into a <code>Task&lt;string&gt;</code>. Perhaps you've noticed that these two examples closely resemble the equivalent <a href="http://blog.ploeh.dk/2018/09/10/the-lazy-functor">Lazy functor examples</a>. The resemblance isn't coincidental. The same <em>abstraction</em> is in use in both places. This is the <em>functor</em> abstraction. That's what this article series is all about, after all. </p> <p> The difference between the Task functor and the Lazy functor is that lazy computations don't run until forced. Tasks, on the other hand, typically start running in the background when created. Thus, when you finally <code>await</code> the value, you may actually not have to wait for it. This does, however, depend on how you created the initial task. </p> <h3 id="8d66efff8d5a4e73b3007878b3ec7227"> First functor law for Task <a href="#8d66efff8d5a4e73b3007878b3ec7227" 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 to the realm of computer science. Instead of proving that the law holds, you can use property-based testing to demonstrate that it does. 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;TaskObeysFirstFunctorLaw(<span style="color:blue;">int</span>&nbsp;i) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;&nbsp;left&nbsp;=&nbsp;<span style="color:#2b91af;">Task</span>.FromResult(i); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;right&nbsp;=&nbsp;<span style="color:#2b91af;">Task</span>.FromResult(i).Select(x&nbsp;=&gt;&nbsp;x); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(left.Result,&nbsp;right.Result); }</pre> </p> <p> This property accesses the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1.result">Result property</a> of the Tasks involved. This is typically not the preferred way to pull the value of Tasks, but I decided to do it like this since <a href="https://github.com/fscheck/FsCheck/issues/167">FsCheck 2.4.0 doesn't support asynchronous properties</a>. </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>Task&lt;int&gt;</code>, not that it holds for <code>Task&lt;string&gt;</code>, <code>Task&lt;Product&gt;</code>, etcetera. </p> <h3 id="12b3ea8d8963414496a6c695f130a4b9"> Second functor law for Task <a href="#12b3ea8d8963414496a6c695f130a4b9" 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;TaskObeysSecondFunctorLaw( &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;&nbsp;left&nbsp;=&nbsp;<span style="color:#2b91af;">Task</span>.FromResult(i).Select(g).Select(f); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;right&nbsp;=&nbsp;<span style="color:#2b91af;">Task</span>.FromResult(i).Select(x&nbsp;=&gt;&nbsp;f(g(x))); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(left.Result,&nbsp;right.Result); }</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 Task in one or two steps. The output is the same in both cases. </p> <h3 id="d87480f7e0124db18b22aaacbff3672a"> Async functor <a href="#d87480f7e0124db18b22aaacbff3672a" title="permalink">#</a> </h3> <p> F# had asynchronous workflows long before C#, so it uses a slightly different model, supported by separate types. Instead of <code>Task&lt;T&gt;</code>, F# relies on a generic type called <a href="https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/control.async%5b%27t%5d-type-%5bfsharp%5d">Async&lt;'T&gt;</a>. It's still a functor, since you can trivially implement a <code>map</code> function for it: </p> <p> <pre><span style="color:blue;">module</span>&nbsp;Async&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;&#39;a&nbsp;-&gt;&nbsp;Async&lt;&#39;a&gt;</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;fromValue&nbsp;x&nbsp;=&nbsp;async&nbsp;{&nbsp;<span style="color:blue;">return</span>&nbsp;x&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;(&#39;a&nbsp;-&gt;&nbsp;&#39;b)&nbsp;-&gt;&nbsp;Async&lt;&#39;a&gt;&nbsp;-&gt;&nbsp;Async&lt;&#39;b&gt;</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;map&nbsp;f&nbsp;x&nbsp;=&nbsp;async&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;x&#39;&nbsp;=&nbsp;x &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;f&nbsp;x&#39;&nbsp;}</pre> </p> <p> The <code>map</code> function uses the <code>async</code> <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/computation-expressions">computation expression</a> to access the value being computed asynchronously. You can use a <code>let!</code> binding to await the value computed in <code>x</code>, and then use the function <code>f</code> to translate that value. The <code>return</code> keyword turns the result into a new <code>Async</code> value. </p> <p> With the <code>map</code> function, you can write code like this: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;(x&nbsp;:&nbsp;Async&lt;int&gt;)&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:blue;">let</span>&nbsp;(y&nbsp;:&nbsp;Async&lt;string&gt;)&nbsp;=&nbsp;x&nbsp;|&gt;&nbsp;Async.map&nbsp;string</pre> </p> <p> Once you've composed an asynchronous workflow to your liking, you can run it to compute the value in which you're interested: </p> <p> <pre>&gt; Async.RunSynchronously y;; val it : string = "42"</pre> </p> <p> This is the main difference between F# asynchronous workflows and .NET Tasks. You have to explicitly run an asynchronous workflows, whereas Tasks are usually, implicitly, already running in the background. </p> <h3 id="f572e55512ab484584450dc0af7fe9b3"> First functor law for Async <a href="#f572e55512ab484584450dc0af7fe9b3" title="permalink">#</a> </h3> <p> The <code>Async.map</code> function obeys the first functor law. Like above, you can use FsCheck to demonstrate how that works: </p> <p> <pre>[&lt;Property(QuietOnSuccess&nbsp;=&nbsp;<span style="color:blue;">true</span>)&gt;] <span style="color:blue;">let</span>&nbsp;``Async&nbsp;obeys&nbsp;first&nbsp;functor&nbsp;law``&nbsp;(i&nbsp;:&nbsp;int)&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;&nbsp;left&nbsp;=&nbsp;Async.fromValue&nbsp;i &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;right&nbsp;=&nbsp;Async.fromValue&nbsp;i&nbsp;|&gt;&nbsp;Async.map&nbsp;id &nbsp;&nbsp;&nbsp;&nbsp;Async.RunSynchronously&nbsp;left&nbsp;=!&nbsp;Async.RunSynchronously&nbsp;right</pre> </p> <p> In addition to FsCheck and xUnit.net, this property also uses <a href="https://github.com/SwensenSoftware/unquote">Unquote</a> 4.0.0 for the assertion. The <code>=!</code> operator is an assertion that the left-hand side <em>must equal</em> the right-hand side. If it doesn't, then the operator throws a descriptive exception. </p> <h3 id="6fd1ba5d9c0647c49ba06d7580b2c552"> Second functor law for Async <a href="#6fd1ba5d9c0647c49ba06d7580b2c552" 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>[&lt;Property(QuietOnSuccess&nbsp;=&nbsp;<span style="color:blue;">true</span>)&gt;] <span style="color:blue;">let</span>&nbsp;``Async&nbsp;obeys&nbsp;second&nbsp;functor&nbsp;law``&nbsp;(f&nbsp;:&nbsp;string&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;byte)&nbsp;g&nbsp;(i&nbsp;:&nbsp;int)&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;&nbsp;left&nbsp;=&nbsp;Async.fromValue&nbsp;i&nbsp;|&gt;&nbsp;Async.map&nbsp;g&nbsp;|&gt;&nbsp;Async.map&nbsp;f &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;right&nbsp;=&nbsp;Async.fromValue&nbsp;i&nbsp;|&gt;&nbsp;Async.map&nbsp;(g&nbsp;&gt;&gt;&nbsp;f) &nbsp;&nbsp;&nbsp;&nbsp;Async.RunSynchronously&nbsp;left&nbsp;=!&nbsp;Async.RunSynchronously&nbsp;right</pre> </p> <p> As usual, the second functor law states that given two arbitrary (but <a href="https://en.wikipedia.org/wiki/Pure_function">pure</a>) functions <code>f</code> and <code>g</code>, it doesn't matter if you map an asynchronous workflow in one or two steps. There could be a difference in performance, but the functor laws don't concern themselves with the time dimension. </p> <p> Both of the above properties use the <code>Async.fromValue</code> helper function to create <code>Async</code> values. Perhaps you consider it cheating that it immediately produces a value, but you can add a delay if you want to pretend that actual asynchronous computation takes place. It'll make the tests run slower, but otherwise will not affect the outcome. </p> <h3 id="9ad596ae1e5f483cb6d02ad963a0a378"> Task and Async isomorphism <a href="#9ad596ae1e5f483cb6d02ad963a0a378" title="permalink">#</a> </h3> <p> The reason I've covered both <code>Task&lt;T&gt;</code> and <code>Async&lt;'a&gt;</code> in the same article is that they're equivalent. You can translate a Task to an asynchronous workflow, or the other way around. </p> <p> <img src="/content/binary/equivalence-of-task-and-async.png" alt="Equivalence of Task and Async."> </p> <p> There's performance implications of going back and forth between <code>Task&lt;T&gt;</code> and <code>Async&lt;'a&gt;</code>, but there's no loss of information. You can, therefore, consider these to representations of asynchronous computations <a href="http://blog.ploeh.dk/2018/01/08/software-design-isomorphisms">isomorphic</a>. </p> <h3 id="4bb86c51ae37462b94e278247d33f8f5"> Summary <a href="#4bb86c51ae37462b94e278247d33f8f5" title="permalink">#</a> </h3> <p> Whether you do asynchronous programming with <code>Task&lt;T&gt;</code> or <code>Async&lt;'a&gt;</code>, asynchronous computations form functors. This enables you to piecemeal compose asynchronous workflows. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/10/01/applicative-functors">Applicative 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>. 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 class="comment" id="8647083ea6c748b6bd2363790a9a69db"> <div class="comment-author">Radek Kapka</div> <div class="comment-content"> <blockquote> <p>Perhaps you&#39;re now convinced that typing speed may not be the bottleneck, but you still feel that you don&#39;t like the verbose <code>Reservation</code> alternative. More code could be an increased maintenance burden. 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.</p> </blockquote> <p>You could create a more generic <code>With</code> method that would enable modifying any property. Here is an alternative design of the <code>Reservation</code> class including such a method. It is untested, so it might not work properly in every case.</p> <pre><code>public sealed class Reservation { public Reservation( DateTimeOffset date, string name, string email, int quantity) : this(date, name, email, quantity, false) { } private Reservation( DateTimeOffset date, string name, string email, int quantity, bool isAccepted) { Date = date; Name = name; Email = email; Quantity = quantity; IsAccepted = isAccepted; } private Reservation() { } public DateTimeOffset Date { get; private set; } public string Name { get; private set; } public string Email { get; private set; } public int Quantity { get; private set; } public bool IsAccepted { get; private set; } public Reservation With(string propertyName, object value) { if (propertyName == null) { throw new ArgumentNullException(nameof(propertyName)); } var property = typeof(Reservation).GetProperty(propertyName); if (property == null) { throw new ArgumentException($"Property ${propertyName} does not exist."); } if (!IsAssignable(property, value)) { throw new ArgumentException($"Value ${value} is not assignable to property ${propertyName}"); } var result = new Reservation(); foreach (var prop in typeof(Reservation).GetProperties()) { prop.SetValue(result, prop.Name == propertyName ? value : prop.GetValue(this)); } return result; } public Reservation Accept() { return new Reservation(Date, Name, Email, Quantity, true); } public override bool Equals(object obj) { if (!(obj is Reservation other)) return false; return Equals(Date, other.Date) &amp;&amp; Equals(Name, other.Name) &amp;&amp; Equals(Email, other.Email) &amp;&amp; Equals(Quantity, other.Quantity) &amp;&amp; Equals(IsAccepted, other.IsAccepted); } public override int GetHashCode() { return Date.GetHashCode() ^ Name.GetHashCode() ^ Email.GetHashCode() ^ Quantity.GetHashCode() ^ IsAccepted.GetHashCode(); } private static bool IsAssignable(PropertyInfo property, object value) { if (value == null &amp;&amp; property.PropertyType.IsValueType &amp;&amp; Nullable.GetUnderlyingType(property.PropertyType) == null) { return false; } return value == null || property.PropertyType.IsAssignableFrom(value.GetType()); } } </code></pre><p>Of course this design is not type-safe and we are throwing exceptions whenever the types of property and value don&#39;t match. Property names can be passed using <code>nameof</code> which will provide compile-time feedback. I believe it would be possible to write a code analyzer that would help calling the <code>With</code> method by raising compilation errors whenever the types don&#39;t match. The <code>With</code> method could be even designed as an extension method on <code>object</code> and distributed in a Nuget package with the anayler alongside it.</p> </div> <div class="comment-date">2018-09-27 07:34 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> <a href="http://blog.ploeh.dk/2018/09/24/asynchronous-functors">Asynchronous 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>. 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 <a href="http://blog.ploeh.dk/2018/10/01/applicative-functors">applicative functors</a> 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