ploeh blog 2019-01-21T17:27:15+00:00 Mark Seemann danish software design http://blog.ploeh.dk Some thoughts on anti-patterns http://blog.ploeh.dk/2019/01/21/some-thoughts-on-anti-patterns 2019-01-21T07:30:00+00:00 Mark Seemann <div id="post"> <p> <em>What's an anti-pattern? Are there rules to identify them, or is it just name-calling? Before I use the term, I try to apply some rules of thumb.</em> </p> <p> It takes time to write a book. Months, even years. It took me two years to write the first edition of <a href="http://amzn.to/12p90MG">Dependency Injection in .NET</a>. The <a href="https://amzn.to/2TE8tJx">second edition of Dependency Injection in .NET</a> is also the result of much work; not so much by me, but by my co-author <a href="http://www.cuttingedge.it/blogs/steven">Steven van Deursen</a>. </p> <p> When you write a book single-handedly, you can be as opinionated as you'd like. When you have a co-author, regardless of how much you think alike, there's bound to be some disagreements. Steven and I agreed about most of the changes we'd like to make to the second edition, but each of us had to yield or compromise a few times. </p> <p> An interesting experience has been that on more than one occasion where I've reluctantly had to yield to Steven, over the time, I've come to appreciate his position. Two minds think better than one. </p> <h3 id="6497bdfd47db433c92a6ec4fabfd4e92"> Ambient Context <a href="#6497bdfd47db433c92a6ec4fabfd4e92" title="permalink">#</a> </h3> <p> One of the changes that Steven wanted to make was that he wanted to change the status of the <em>Ambient Context</em> pattern to an anti-pattern. While I never use that pattern myself, I included it in the first edition in the spirit of the original <a href="http://amzn.to/XBYukB">Design Patterns</a> book. The <em>Gang of Four</em> made it clear that the patterns they'd described weren't invented, but rather discovered: <blockquote> <p> "We have included only designs that have been applied more than once in different systems." </p> <footer><cite>Gamma et al, <em>Design Patterns</em>, 1994, p. 2</cite></footer> </blockquote> The spirit, as I understand it, is to identify solutions that already exist, and catalogue them. When I wrote the first edition of my book, I tried to do that as well. </p> <p> I'd noticed what I eventually named the <em>Ambient Context</em> pattern several places in the .NET Base Class Library. Some of those APIs are still around today. <a href="https://docs.microsoft.com/dotnet/api/system.threading.thread.currentprincipal">Thread.CurrentPrincipal</a>, <a href="https://docs.microsoft.com/dotnet/api/system.globalization.cultureinfo.currentculture">CultureInfo.CurrentCulture</a>, <a href="https://en.wikipedia.org/wiki/Thread-local_storage">thread-local storage</a>, <a href="https://docs.microsoft.com/dotnet/api/system.web.httpcontext.current">HttpContext.Current</a>, and so on. </p> <p> None of these really have anything to do with Dependency Injection (DI), but people sometimes attempt to use them to solve problems similar to the problems that DI addresses. For that reason, and because the pattern was so prevalent, I included it in the book - as a pattern, not an anti-pattern. </p> <p> Steven wanted to make it an anti-pattern, and I conceded. I wasn't sure I was ready to explicitly call it out as an anti-pattern, but I agreed to the change. I'm becoming increasingly happy that Steven talked me into it. </p> <h3 id="08fbf0fd59154a57bbba936128f6c60e"> Pareto efficiency <a href="#08fbf0fd59154a57bbba936128f6c60e" title="permalink">#</a> </h3> <p> I've heard said of me that I'm one of those people who call everything I don't like an anti-pattern. I don't think that's true. </p> <p> I think people's perception of me is skewed because even today, the most visited page (my greatest hit, if you will) is an article called <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern">Service Locator is an Anti-Pattern</a>. (It concerns me a bit that an article from 2010 seems to be my crowning achievement. I hope I haven't peaked yet, but the numbers tell a different tale.) </p> <p> While I've used the term <em>anti-pattern</em> in other connections, I prefer to be conservative with my use of the word. I tend to use it only when I feel confident that something is, indeed, an anti-pattern. </p> <p> What's an anti-pattern? <a href="https://amzn.to/2VHDX3m">AntiPatterns</a> defines it like this: <blockquote> <p> "An AntiPattern is a literary form that describes a commonly occurring solution to a problem that generates decidedly negative consequences." </p> <footer><cite>Brown et al, <em>AntiPatterns</em>, 1998, p. 7</cite></footer> </blockquote> As definitions go, it's quite amphibolous. Is it the problem that generates negative consequences? Hardly. In the context, it's clear that it's the solution that causes problems. In any case, just because it's in a book doesn't necessarily make it right, but I find it a good start. </p> <p> I think that the phrase <em>decidedly negative consequences</em> is key. Most solutions come with <em>some</em> disadvantages, but in order for a 'solution' to be an anti-pattern, the disadvantages must clearly outweigh any advantages produced. </p> <p> I usually look at it another way. If I can solve the problem in a different way that generates at least as many advantages, but fewer disadvantages, then the first 'solution' might be an anti-pattern. This way of viewing the problem may stem from my background in economics. In that perspective, an anti-pattern simply isn't <a href="https://en.wikipedia.org/wiki/Pareto_efficiency">Pareto optimal</a>. </p> <h3 id="eb04af30ae5b40529fda1588525aee6d"> Falsifiability <a href="#eb04af30ae5b40529fda1588525aee6d" title="permalink">#</a> </h3> <p> Another rule of thumb I employ to determine whether a solution could be an anti-pattern is <a href="https://en.wikipedia.org/wiki/Karl_Popper">Popper</a>'s concept of <a href="https://en.wikipedia.org/wiki/Falsifiability">falsifiability</a>. As a continuation of the Pareto efficiency perspective, an anti-pattern is a 'solution' that you can improve without any (significant) trade-offs. </p> <p> That turns claims about anti-patterns into falsifiable statements, which I consider is the most intellectually honest way to go about claiming that things are bad. </p> <p> Take, for example, the claim that <em>Service Locator is an anti-pattern</em>. In light of Pareto efficiency, that's a falsifiable claim. All you have to do to prove me wrong is to present a situation where Service Locator solves a problem, and I can't come up with a better solution. </p> <p> I made the claim about Service Locator in 2010, and so far, no one has been able to present such a situation, even though several have tried. I'm fairly confident making that claim. </p> <p> This way of looking at the term anti-pattern, however, makes me wary of declaiming solutions anti-patterns just because I don't like them. Could there be a counter-argument, some niche scenario, where the pattern actually couldn't be improved without trade-offs? </p> <p> I didn't take it lightly when Steven suggested making Ambient Context an anti-pattern. </p> <h3 id="e027fe12038c4160a3be19bce065cd74"> Preliminary status <a href="#e027fe12038c4160a3be19bce065cd74" title="permalink">#</a> </h3> <p> I've had some time to think about Ambient Context since I had the (civil) discussion with Steven. The more I think about it, the more I think that he's right; that Ambient Context really <em>is</em> an anti-pattern. </p> <p> I never use that pattern myself, so it's clear to me that for all the situations that I typically encounter, there's always better solutions, with no significant trade-offs. </p> <p> The question is: could there be some niche scenario that I'm not aware of, where Ambient Context is a bona fide good solution? </p> <p> The more I think about this, the more I'm beginning to believe that there isn't. It remains to be seen, though. It remains to be falsified. </p> <h3 id="ed7478fa76324922a5543964e9c8c48e"> Summary <a href="#ed7478fa76324922a5543964e9c8c48e" title="permalink">#</a> </h3> <p> I'm so happy that Steven van Deursen agreed to co-author the second edition of <em>Dependency Injection in .NET</em> with me. The few areas where we've disagreed, I've ultimately come around to agree with him. He's truly taken a good book and made it better. </p> <p> One of the changes is that Ambient Context is now classified as an anti-pattern. Originally, I wasn't sure that this was the correct thing to do, but I've since changed my mind. I do think that Ambient Context belongs in the anti-patterns chapter. </p> <p> I could be wrong, though. I was before. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="4493b077ecd84d6d8217d4944e11471a"> <div class="comment-author"><a href="https://rebus.fm">Mogens Heller Grabe</a></div> <div class="comment-content"> <p> Thanks for great input for discussion :P </p> <p> Like with all other patterns and anti-patterns, I think there's a time and a place. </p> <p> Simply looking at it in a one-dimensional manner, i.e. asking "does there exist a solution to this problem with the same advantages but less downsides?" must be qualified with "IN THIS TIME AND PLACE", in my opinion. </p> <p> This way, the patterns/anti-patterns distinction does not make that much sense in a global perspective, because all patterns can be an anti-patterns in some situations, and vice versa. </p> <p> For example, I like what <em>Ambient Context</em> does in <a href="https://github.com/rebus-org/Rebus">Rebus</a>: It provides a mechanism that enables user code to transparently enlist its bus operations in a unit of work, without requiring user code to pass that unit of work to each operation. </p> <p> This is very handy, e.g. in OWIN-based applications, where the unit of work can be managed by an OWIN middleware that uses a <a href="https://github.com/rebus-org/Rebus/wiki/Transactions#i-am-not-in-a-transaction---i-want-to-either-publish-a-message-or-send-several-messages"><code>RebusTransactionScope</code></a>, this way enlisting all send/publish operations on the bus in that unit of work. </p> <p> Had it not been possible to automatically pick up an ongoing ambient Rebus transaction context, one would probably need to pollute the interfaces of one's application with an <code>ITransactionContext</code> argument, thus not handling the cross-cutting concern of managing the unit of work in a cross-cutting manner. </p> </div> <div class="comment-date">2019-01-21 12:37 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please consider <a href="http://blog.ploeh.dk/support">supporting it</a>. An Either functor http://blog.ploeh.dk/2019/01/14/an-either-functor 2019-01-14T07:27:00+00:00 Mark Seemann <div id="post"> <p> <em>Either forms a normal functor. A placeholder 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>. As another article explains, <a href="http://blog.ploeh.dk/2019/01/07/either-bifunctor">Either is a bifunctor</a>. This makes it trivially a functor. As such, this article is mostly a place-holder to fit the spot in the <em>functor table of contents</em>, thereby indicating that Either is a functor. </p> <p> Since Either is a bifunctor, it's actually not one, but two, functors. Many languages, C# included, are best equipped to deal with unambiguous functors. This is also true in <a href="https://haskell.org">Haskell</a>, where <code>Either l r</code> is only a <code>Functor</code> over the right side. Likewise, in C#, you can make <code>IEither&lt;L, R&gt;</code> a functor by implementing <code>Select</code>: </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;">L</span>,&nbsp;<span style="color:#2b91af;">R1</span>&gt;&nbsp;Select&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">R</span>,&nbsp;<span style="color:#2b91af;">R1</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IEither</span>&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">R</span>&gt;&nbsp;source, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">R</span>,&nbsp;<span style="color:#2b91af;">R1</span>&gt;&nbsp;selector) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;source.SelectRight(selector); }</pre> </p> <p> This method simply delegates all implementation to the <code>SelectRight</code> method; it's just <code>SelectRight</code> by another name. It obeys the functor laws, since these are just specializations of the bifunctor laws, and we know that Either is a proper bifunctor. </p> <p> It would have been technically possible to instead implement a <code>Select</code> method by calling <code>SelectLeft</code>, but it seems generally more useful to enable syntactic sugar for mapping over 'happy path' scenarios. This enables you to write projections over operations that can fail. </p> <p> Here's some <em>C# Interactive</em> examples that use the <code>FindWinner</code> helper method from <a href="http://blog.ploeh.dk/2018/06/11/church-encoded-either">the Church-encoded Either article</a>. Imagine that you're collecting votes; you're trying to pick the highest-voted integer, but in reality, you're only interested in seeing if the number is positive or not. Since <code>FindWinner</code> returns <code>IEither&lt;VoteError, T&gt;</code>, and this type is a functor, you can project the right result, while any left result short-circuits the query. First, here's a successful query: </p> <p> <pre>&gt; <span style="color:blue;">from</span>&nbsp;i&nbsp;<span style="color:blue;">in</span>&nbsp;FindWinner(1,&nbsp;2,&nbsp;-3,&nbsp;-1,&nbsp;2,&nbsp;-1,&nbsp;-1)&nbsp;<span style="color:blue;">select</span>&nbsp;i&nbsp;&gt;&nbsp;0 Right&lt;VoteError, bool&gt;(false)</pre> </p> <p> This query succeeds, resulting in a <code>Right</code> object. The contained value is <code>false</code> because the winner of the vote is <code>-1</code>, which isn't a positive number. </p> <p> On the other hand, the following query fails because of a tie. </p> <p> <pre>&gt; <span style="color:blue;">from</span>&nbsp;i&nbsp;<span style="color:blue;">in</span>&nbsp;FindWinner(1,&nbsp;2,&nbsp;-3,&nbsp;-1,&nbsp;2,&nbsp;-1)&nbsp;<span style="color:blue;">select</span>&nbsp;i&nbsp;&gt;&nbsp;0 Left&lt;VoteError, bool&gt;(Tie)</pre> </p> <p> Because the result is tied on <code>-1</code>, the return value is a <code>Left</code> object containing the <code>VoteError</code> value <code>Tie</code>. </p> <p> Another source of error is an empty input collection: </p> <p> <pre>&gt; <span style="color:blue;">from</span>&nbsp;i&nbsp;<span style="color:blue;">in</span>&nbsp;FindWinner&lt;<span style="color:blue;">int</span>&gt;()&nbsp;<span style="color:blue;">select</span>&nbsp;i&nbsp;&gt;&nbsp;0 Left&lt;VoteError, bool&gt;(Empty)</pre> </p> <p> This time, the <code>Left</code> object contains the <code>Empty</code> error value, since no winner can be found from an empty collection. </p> <p> While the <code>Select</code> method doesn't implement any behaviour that <code>SelectRight</code> doesn't already afford, it enables you to use C# query syntax, as demonstrated by the above examples. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/08/06/a-tree-functor">A Tree functor</a>. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="http://blog.ploeh.dk/support">supporting it</a>. Either bifunctor http://blog.ploeh.dk/2019/01/07/either-bifunctor 2019-01-07T09:13:00+00:00 Mark Seemann <div id="post"> <p> <em>Either forms a bifunctor. An article for object-oriented programmers.</em> </p> <p> This article is an instalment in <a href="http://blog.ploeh.dk/2018/12/24/bifunctors">an article series about bifunctors</a>. As the overview article explains, essentially there's two practically useful bifunctors: pairs and <a href="http://blog.ploeh.dk/2018/06/11/church-encoded-either">Either</a>. In <a href="http://blog.ploeh.dk/2018/12/31/tuple-bifunctor">the previous article</a>, you saw how a pair (a two-tuple) forms a bifunctor. In this article, you'll see how Either also forms a bifunctor. </p> <h3 id="b30721a6a66a427eb1a7159d66290337"> Mapping both dimensions <a href="#b30721a6a66a427eb1a7159d66290337" title="permalink">#</a> </h3> <p> In the previous article, you saw how, if you have maps over both dimensions, you can trivially implement <code>SelectBoth</code> (what <a href="https://www.haskell.org">Haskell</a> calls <code>bimap</code>): </p> <p> <pre><span style="color:blue;">return</span>&nbsp;source.SelectFirst(selector1).SelectSecond(selector2);</pre> </p> <p> The relationship can, however, go both ways. If you implement <code>SelectBoth</code>, you can derive <code>SelectFirst</code> and <code>SelectSecond</code> from it. In this article, you'll see how to do that for Either. </p> <p> Given the <a href="http://blog.ploeh.dk/2018/06/11/church-encoded-either">Church-encoded Either</a>, the implementation of <code>SelectBoth</code> can be achieved in a single expression: </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;">L1</span>,&nbsp;<span style="color:#2b91af;">R1</span>&gt;&nbsp;SelectBoth&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">L1</span>,&nbsp;<span style="color:#2b91af;">R</span>,&nbsp;<span style="color:#2b91af;">R1</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IEither</span>&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">R</span>&gt;&nbsp;source, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">L1</span>&gt;&nbsp;selectLeft, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">R</span>,&nbsp;<span style="color:#2b91af;">R1</span>&gt;&nbsp;selectRight) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;source.Match&lt;<span style="color:#2b91af;">IEither</span>&lt;<span style="color:#2b91af;">L1</span>,&nbsp;<span style="color:#2b91af;">R1</span>&gt;&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;onLeft:&nbsp;&nbsp;l&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;&nbsp;<span style="color:#2b91af;">Left</span>&lt;<span style="color:#2b91af;">L1</span>,&nbsp;<span style="color:#2b91af;">R1</span>&gt;(&nbsp;selectLeft(l)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;onRight:&nbsp;r&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Right</span>&lt;<span style="color:#2b91af;">L1</span>,&nbsp;<span style="color:#2b91af;">R1</span>&gt;(selectRight(r))); }</pre> </p> <p> Given that the input <code>source</code> is an <code>IEither&lt;L, R&gt;</code> object, there's isn't much you can do. That interface only defines a single member, <code>Match</code>, so that's the only method you can call. When you do that, you have to supply the two arguments <code>onLeft</code> and <code>onRight</code>. </p> <p> The <code>Match</code> method is defined like this: </p> <p> <pre><span style="color:#2b91af;">T</span>&nbsp;Match&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">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> Given the desired return type of <code>SelectBoth</code>, you know that <code>T</code> should be <code>IEither&lt;L1, R1&gt;</code>. This means, then, that for <code>onLeft</code>, you must supply a function of the type <code>Func&lt;L, IEither&lt;L1, R1&gt;&gt;</code>. Since a functor is a structure-preserving map, you should translate a <em>left</em> case to a <em>left</em> case, and a <em>right</em> case to a <em>right</em> case. This implies that the concrete return type that matches <code>IEither&lt;L1, R1&gt;</code> for the <code>onLeft</code> argument is <code>Left&lt;L1, R1&gt;</code>. </p> <p> When you write the function with the type <code>Func&lt;L, IEither&lt;L1, R1&gt;&gt;</code> as a lambda expression, the input argument <code>l</code> has the type <code>L</code>. In order to create a <code>new Left&lt;L1, R1&gt;</code>, however, you need an <code>L1</code> object. How do you produce an <code>L1</code> object from an <code>L</code> object? You call <code>selectLeft</code> with <code>l</code>, because <code>selectLeft</code> is a function of the type <code>Func&lt;L, L1&gt;</code>. </p> <p> You can apply the same line of reasoning to the <code>onRight</code> argument. Write a lambda expression that takes an <code>R</code> object <code>r</code> as input, call <code>selectRight</code> to turn that into an <code>R1</code> object, and return it wrapped in a <code>new Right&lt;L1, R1&gt;</code> object. </p> <p> This works as expected: </p> <p> <pre>&gt; <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>).SelectBoth(<span style="color:blue;">string</span>.IsNullOrWhiteSpace,&nbsp;i&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">DateTime</span>(i)) Left&lt;bool, DateTime&gt;(false) &gt; <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;(1337).SelectBoth(<span style="color:blue;">string</span>.IsNullOrWhiteSpace,&nbsp;i&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">DateTime</span>(i)) Right&lt;bool, DateTime&gt;([01.01.0001 00:00:00])</pre> </p> <p> Notice that both of the above statements evaluated in <em>C# Interactive</em> use the same projections as input to <code>SelectBoth</code>. Clearly, though, because the inputs are first a <code>Left</code> value, and secondly a <code>Right</code> value, the outputs differ. </p> <h3 id="10a641d7ad0b44158f74665fd87feb5e"> Mapping the left side <a href="#10a641d7ad0b44158f74665fd87feb5e" title="permalink">#</a> </h3> <p> When you have <code>SelectBoth</code>, you can trivially implement the translations for each dimension in isolation. In the previous article, I called these methods <code>SelectFirst</code> and <code>SelectSecond</code>. In this article, I've chosen to instead name them <code>SelectLeft</code> and <code>SelectRight</code>, but they still corresponds to Haskell's <code>first</code> and <code>second</code> <code>Bifunctor</code> functions. </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;">L1</span>,&nbsp;<span style="color:#2b91af;">R</span>&gt;&nbsp;SelectLeft&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">L1</span>,&nbsp;<span style="color:#2b91af;">R</span>&gt;(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IEither</span>&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">R</span>&gt;&nbsp;source,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">L1</span>&gt;&nbsp;selector) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;source.SelectBoth(selector,&nbsp;r&nbsp;=&gt;&nbsp;r); }</pre> </p> <p> The method body is literally a one-liner. Just call <code>SelectBoth</code> with <code>selector</code> as the projection for the left side, and the identity function as the projection for the right side. This ensures that if the actual value is a <code>Right&lt;L, R&gt;</code> object, nothing's going to happen. Only if the input is a <code>Left&lt;L, R&gt;</code> object will the projection run: </p> <p> <pre>&gt; <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;&quot;</span>).SelectLeft(<span style="color:blue;">string</span>.IsNullOrWhiteSpace) Left&lt;bool, int&gt;(true) &gt; <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;bar&quot;</span>).SelectLeft(<span style="color:blue;">string</span>.IsNullOrWhiteSpace) Left&lt;bool, int&gt;(false) &gt; <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).SelectLeft(<span style="color:blue;">string</span>.IsNullOrWhiteSpace) Right&lt;bool, int&gt;(42)</pre> </p> <p> In the above <em>C# Interactive</em> session, you can see how projecting three different objects using <code>string.IsNullOrWhiteSpace</code> works. When the <code>Left</code> object indeed does contain an empty string, the result is a <code>Left</code> value containing <code>true</code>. When the object contains <code>"bar"</code>, however, it contains <code>false</code>. Furthermore, when the object is a <code>Right</code> value, the mapping has no effect. </p> <h3 id="b9027a241d6444d5b869a8a1b92659c5"> Mapping the right side <a href="#b9027a241d6444d5b869a8a1b92659c5" title="permalink">#</a> </h3> <p> Similar to <code>SelectLeft</code>, you can also trivially implement <code>SelectRight</code>: </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;">L</span>,&nbsp;<span style="color:#2b91af;">R1</span>&gt;&nbsp;SelectRight&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">R</span>,&nbsp;<span style="color:#2b91af;">R1</span>&gt;(<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">IEither</span>&lt;<span style="color:#2b91af;">L</span>,&nbsp;<span style="color:#2b91af;">R</span>&gt;&nbsp;source,&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">R</span>,&nbsp;<span style="color:#2b91af;">R1</span>&gt;&nbsp;selector) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;source.SelectBoth(l&nbsp;=&gt;&nbsp;l,&nbsp;selector); }</pre> </p> <p> This is another one-liner calling <code>SelectBoth</code>, with the difference that the identity function <code>l =&gt; l</code> is passed as the first argument, instead of as the last. This ensures that only <code>Right</code> values are mapped: </p> <p> <pre>&gt; <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;baz&quot;</span>).SelectRight(i&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">DateTime</span>(i)) Left&lt;string, DateTime&gt;("baz") &gt; <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;(1_234_567_890).SelectRight(i&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">DateTime</span>(i)) Right&lt;string, DateTime&gt;([01.01.0001 00:02:03])</pre> </p> <p> In the above examples, <code>Right</code> integers are projected into <code>DateTime</code> values, whereas <code>Left</code> strings stay strings. </p> <h3 id="a80a8d7ebbce46b4914749f46cd99e89"> Identity laws <a href="#a80a8d7ebbce46b4914749f46cd99e89" title="permalink">#</a> </h3> <p> Either obeys all the bifunctor laws. While it's formal work to prove that this is the case, you can get an intuition for it via examples. Often, I use a property-based testing library like <a href="https://fscheck.github.io/FsCheck">FsCheck</a> or <a href="https://github.com/hedgehogqa/fsharp-hedgehog">Hedgehog</a> to demonstrate (not prove) that laws hold, but in this article, I'll keep it simple and only cover each law with a parametrised test. </p> <p> <pre><span style="color:blue;">private</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Id&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">T</span>&nbsp;x)&nbsp;=&gt;&nbsp;x; <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;BifunctorLawsData { &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:blue;">new</span>&nbsp;&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>)&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:blue;">new</span>&nbsp;&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;bar&quot;</span>)&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:blue;">new</span>&nbsp;&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;baz&quot;</span>)&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: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;(&nbsp;&nbsp;&nbsp;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: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;(&nbsp;1337)&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: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;(&nbsp;&nbsp;&nbsp;&nbsp;0)&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;} } [<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">MemberData</span>(<span style="color:blue;">nameof</span>(BifunctorLawsData))] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SelectLeftObeysFirstFunctorLaw(<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;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(e,&nbsp;e.SelectLeft(Id)); }</pre> </p> <p> This test uses <a href="https://xunit.github.io">xUnit.net</a>'s <code>[Theory]</code> feature to supply a small set of example input values. The input values are defined by the <code>BifunctorLawsData</code> property, since I'll reuse the same values for all the bifunctor law demonstration tests. </p> <p> The tests also use the identity function implemented as a <code>private</code> function called <code>Id</code>, since C# doesn't come equipped with such a function in the Base Class Library. </p> <p> For all the <code>IEither&lt;string, int&gt;</code> objects <code>e</code>, the test simply verifies that the original Either <code>e</code> is equal to the Either projected over the first axis with the <code>Id</code> function. </p> <p> Likewise, the first functor law applies when translating over the second dimension: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">MemberData</span>(<span style="color:blue;">nameof</span>(BifunctorLawsData))] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SelectRightObeysFirstFunctorLaw(<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;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(e,&nbsp;e.SelectRight(Id)); }</pre> </p> <p> This is the same test as the previous test, with the only exception that it calls <code>SelectRight</code> instead of <code>SelectLeft</code>. </p> <p> Both <code>SelectLeft</code> and <code>SelectRight</code> are implemented by <code>SelectBoth</code>, so the real test is whether this method obeys the identity law: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">MemberData</span>(<span style="color:blue;">nameof</span>(BifunctorLawsData))] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SelectBothObeysIdentityLaw(<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;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(e,&nbsp;e.SelectBoth(Id,&nbsp;Id)); }</pre> </p> <p> Projecting over both dimensions with the identity function does, indeed, return an object equal to the input object. </p> <h3 id="5ee147f408d64bc78171ade1f968b9aa"> Consistency law <a href="#5ee147f408d64bc78171ade1f968b9aa" title="permalink">#</a> </h3> <p> In general, it shouldn't matter whether you map with <code>SelectBoth</code> or a combination of <code>SelectLeft</code> and <code>SelectRight</code>: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">MemberData</span>(<span style="color:blue;">nameof</span>(BifunctorLawsData))] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;ConsistencyLawHolds(<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;&nbsp;&nbsp;<span style="color:blue;">bool</span>&nbsp;f(<span style="color:blue;">string</span>&nbsp;s)&nbsp;=&gt;&nbsp;<span style="color:blue;">string</span>.IsNullOrWhiteSpace(s); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTime</span>&nbsp;g(<span style="color:blue;">int</span>&nbsp;i)&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">DateTime</span>(i); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(e.SelectBoth(f,&nbsp;g),&nbsp;e.SelectRight(g).SelectLeft(f)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e.SelectLeft(f).SelectRight(g), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e.SelectRight(g).SelectLeft(f)); }</pre> </p> <p> This example creates two local functions <code>f</code> and <code>g</code>. The first function, <code>f</code>, just delegates to <code>string.IsNullOrWhiteSpace</code>, although I want to stress that this is just an example. The law should hold for any two (<a href="https://en.wikipedia.org/wiki/Pure_function">pure</a>) functions. The second function, <code>g</code>, creates a new <code>DateTime</code> object from an integer, using one of the <code>DateTime</code> constructor overloads. </p> <p> The test then verifies that you get the same result from calling <code>SelectBoth</code> as when you call <code>SelectLeft</code> followed by <code>SelectRight</code>, or the other way around. </p> <h3 id="509bf515dac14e0e95346ee604ba26af"> Composition laws <a href="#509bf515dac14e0e95346ee604ba26af" title="permalink">#</a> </h3> <p> The composition laws insist that you can compose functions, or translations, and that again, the choice to do one or the other doesn't matter. Along each of the axes, it's just the second functor law applied. This parametrised test demonstrates that the law holds for <code>SelectLeft</code>: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">MemberData</span>(<span style="color:blue;">nameof</span>(BifunctorLawsData))] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SecondFunctorLawHoldsForSelectLeft(<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;&nbsp;&nbsp;<span style="color:blue;">bool</span>&nbsp;f(<span style="color:blue;">int</span>&nbsp;x)&nbsp;=&gt;&nbsp;x&nbsp;%&nbsp;2&nbsp;==&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;g(<span style="color:blue;">string</span>&nbsp;s)&nbsp;=&gt;&nbsp;s.Length; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(e.SelectLeft(x&nbsp;=&gt;&nbsp;f(g(x))),&nbsp;e.SelectLeft(g).SelectLeft(f)); }</pre> </p> <p> Here, <code>f</code> is the <em>even</em> function, whereas <code>g</code> is a local function that returns the length of a string. The second functor law states that mapping <code>f(g(x))</code> in a single step is equivalent to first mapping over <code>g</code> and then map the result of that using <code>f</code>. </p> <p> The same law applies if you fix the first dimension and translate over the second: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">MemberData</span>(<span style="color:blue;">nameof</span>(BifunctorLawsData))] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SecondFunctorLawHoldsForSelectRight(<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;&nbsp;&nbsp;<span style="color:blue;">char</span>&nbsp;f(<span style="color:blue;">bool</span>&nbsp;b)&nbsp;=&gt;&nbsp;b&nbsp;?&nbsp;<span style="color:#a31515;">&#39;T&#39;</span>&nbsp;:&nbsp;<span style="color:#a31515;">&#39;F&#39;</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">bool</span>&nbsp;g(<span style="color:blue;">int</span>&nbsp;i)&nbsp;=&gt;&nbsp;i&nbsp;%&nbsp;2&nbsp;==&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(e.SelectRight(x&nbsp;=&gt;&nbsp;f(g(x))),&nbsp;e.SelectRight(g).SelectRight(f)); }</pre> </p> <p> Here, <code>f</code> is a local function that returns <code>'T'</code> for <code>true</code> and <code>'F'</code> for <code>false</code>, and <code>g</code> is a local function that, as you've seen before, determines whether a number is even. Again, the test demonstrates that the output is the same whether you map over an intermediary step, or whether you map using only a single step. </p> <p> This generalises to the composition law for <code>SelectBoth</code>: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>,&nbsp;<span style="color:#2b91af;">MemberData</span>(<span style="color:blue;">nameof</span>(BifunctorLawsData))] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SelectBothCompositionLawHolds(<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;&nbsp;&nbsp;<span style="color:blue;">bool</span>&nbsp;f(<span style="color:blue;">int</span>&nbsp;x)&nbsp;=&gt;&nbsp;x&nbsp;%&nbsp;2&nbsp;==&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;g(<span style="color:blue;">string</span>&nbsp;s)&nbsp;=&gt;&nbsp;s.Length; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">char</span>&nbsp;h(<span style="color:blue;">bool</span>&nbsp;b)&nbsp;=&gt;&nbsp;b&nbsp;?&nbsp;<span style="color:#a31515;">&#39;T&#39;</span>&nbsp;:&nbsp;<span style="color:#a31515;">&#39;F&#39;</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">bool</span>&nbsp;i(<span style="color:blue;">int</span>&nbsp;x)&nbsp;=&gt;&nbsp;x&nbsp;%&nbsp;2&nbsp;==&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e.SelectBoth(x&nbsp;=&gt;&nbsp;f(g(x)),&nbsp;y&nbsp;=&gt;&nbsp;h(i(y))), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e.SelectBoth(g,&nbsp;i).SelectBoth(f,&nbsp;h)); }</pre> </p> <p> Again, whether you translate in one or two steps shouldn't affect the outcome. </p> <p> As all of these tests demonstrate, the bifunctor laws hold for Either. The tests only showcase six examples for either a string or an integer, but I hope it gives you an intuition how any Either object is a bifunctor. After all, the <code>SelectLeft</code>, <code>SelectRight</code>, and <code>SelectBoth</code> methods are all generic, and they behave the same for all generic type arguments. </p> <h3 id="7b8babee4af64eeaa93fe4562ed721bd"> Summary <a href="#7b8babee4af64eeaa93fe4562ed721bd" title="permalink">#</a> </h3> <p> Either objects are bifunctors. You can translate the first and second dimension of an Either object independently of each other, and the bifunctor laws hold for any pure translation, no matter how you compose the projections. </p> <p> As always, there can be performance differences between the various compositions, but the outputs will be the same regardless of composition. </p> <p> A functor, and by extension, a bifunctor, is a structure-preserving map. This means that any projection preserves the structure of the underlying container. For Either objects, it means that <em>left</em> objects remain <em>left</em> objects, and <em>right</em> objects remain <em>right</em> objects, even if the contained values change. Either is characterised by containing exactly one value, but it can be either a <em>left</em> value or a <em>right</em> value. No matter how you translate it, it still contains only a single value - <em>left</em> or <em>right</em>. </p> <p> The other common bifunctor, <em>pair</em>, is complementary. Not only does it also have two dimensions, but a pair always contains both values at once. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/01/08/software-design-isomorphisms">Software design isomorphisms</a> </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="http://blog.ploeh.dk/support">supporting it</a>. Tuple bifunctor http://blog.ploeh.dk/2018/12/31/tuple-bifunctor 2018-12-31T12:13:00+00:00 Mark Seemann <div id="post"> <p> <em>A Pair (a two-tuple) forms a bifunctor. An article for object-oriented programmers.</em> </p> <p> This article is an instalment in <a href="http://blog.ploeh.dk/2018/12/24/bifunctors">an article series about bifunctors</a>. In the previous overview, you learned about the general concept of a bifunctor. In practice, there's two useful bifunctor instances: pairs (two-tuples) and <a href="http://blog.ploeh.dk/2018/06/11/church-encoded-either">Either</a>. In this article, you'll see how a pair is a bifunctor, and in the next article, you'll see how Either fits the same abstraction. </p> <h3 id="d918d0271c33406ba3047ef162212100"> Tuple as a functor <a href="#d918d0271c33406ba3047ef162212100" title="permalink">#</a> </h3> <p> You can treat a normal pair (two-tuple) as a <a href="http://blog.ploeh.dk/2018/03/22/functors">functor</a> by mapping one of the elements, while keeping the other generic type fixed. In <a href="https://www.haskell.org">Haskell</a>, when you have types with multiple type arguments, you often 'fix' the types from the left, leaving the right-most type free to vary. Doing this for a pair, which in C# has the type <code>Tuple&lt;T, U&gt;</code>, this means that tuples are functors if we keep <code>T</code> fixed and enable translation of the second element from <code>U1</code> to <code>U2</code>. </p> <p> This is easy to implement with a standard <code>Select</code> extension method: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">U2</span>&gt;&nbsp;Select&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">U1</span>,&nbsp;<span style="color:#2b91af;">U2</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">U1</span>&gt;&nbsp;source, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">U1</span>,&nbsp;<span style="color:#2b91af;">U2</span>&gt;&nbsp;selector) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">Tuple</span>.Create(source.Item1,&nbsp;selector(source.Item2)); }</pre> </p> <p> You simply return a new tuple by carrying <code>source.Item1</code> over without modification, while on the other hand calling <code>selector</code> with <code>source.Item2</code>. Here's a simple example, which also highlights that C# understands functors: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;t&nbsp;=&nbsp;<span style="color:#2b91af;">Tuple</span>.Create(<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;42); <span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;<span style="color:blue;">from</span>&nbsp;i&nbsp;<span style="color:blue;">in</span>&nbsp;t &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;i&nbsp;%&nbsp;2&nbsp;==&nbsp;0;</pre> </p> <p> Here, <code>actual</code> is a <code>Tuple&lt;string, bool&gt;</code> with the values <code>"foo"</code> and <code>true</code>. Inside the query expression, <code>i</code> is an <code>int</code>, and the <code>select</code> expression returns a <code>bool</code> value indicating whether the number is even or odd. Notice that the <code>string</code> in the first element disappears inside the query expression. It's still there, but the code inside the query expression can't see <code>"foo"</code>. </p> <h3 id="589f054d8dab47a4bb308951ee76f96b"> Mapping the first element <a href="#589f054d8dab47a4bb308951ee76f96b" title="permalink">#</a> </h3> <p> There's no technical reason why the mapping has to be over the second element; it's just how Haskell does it by convention. There are other, more philosophical reasons for that convention, but in the end, they boil down to the ultimately arbitrary cultural choice of reading from left to right (in Western scripts). </p> <p> You can translate the first element of a tuple as easily: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">U</span>&gt;&nbsp;SelectFirst&lt;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">U</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">U</span>&gt;&nbsp;source, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">T2</span>&gt;&nbsp;selector) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">Tuple</span>.Create(selector(source.Item1),&nbsp;source.Item2); }</pre> </p> <p> While, technically, you <em>can</em> call this method <code>Select</code>, this can confuse the C# compiler's overload resolution system - at least if you have a tuple of two identical types (e.g. <code>Tuple&lt;int, int&gt;</code> or <code>Tuple&lt;string, string&gt;</code>). In order to avoid that sort of confusion, I decided to give the method another name, and in keeping with how C# LINQ methods tend to get names, I thought <code>SelectFirst</code> sounded reasonable. </p> <p> In Haskell, this function is called <code>first</code>, and is part of the <code>Bifunctor</code> type class: </p> <p> <pre>Prelude Data.Bifunctor&gt; first (even . length) ("foo", 42) (False,42)</pre> </p> <p> In C#, you can perform the same translation using the above <code>SelectFirst</code> extension method: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;t&nbsp;=&nbsp;<span style="color:#2b91af;">Tuple</span>.Create(<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;42); <span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;t.SelectFirst(s&nbsp;=&gt;&nbsp;s.Length&nbsp;%&nbsp;2&nbsp;==&nbsp;0);</pre> </p> <p> This also returns a <code>Tuple&lt;bool, int&gt;</code> containing the values <code>false</code> and <code>42</code>. Notice that in this case, the first element <code>"foo"</code> is translated into <code>false</code> (because its length is odd), while the second element <code>42</code> carries over unchanged. </p> <h3 id="7da2d817bebb40cbb2221212158324f8"> Mapping the second element <a href="#7da2d817bebb40cbb2221212158324f8" title="permalink">#</a> </h3> <p> You've already seen how the above <code>Select</code> method maps over the second element of a pair. This means that you can already map over both dimensions of the bifunctor, but perhaps, for consistency's sake, you'd also like to add an explicit <code>SelectSecond</code> method. This is now trivial to implement, since it can delegate its work to <code>Select</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">U2</span>&gt;&nbsp;SelectSecond&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">U1</span>,&nbsp;<span style="color:#2b91af;">U2</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">U1</span>&gt;&nbsp;source, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">U1</span>,&nbsp;<span style="color:#2b91af;">U2</span>&gt;&nbsp;selector) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;source.Select(selector); }</pre> </p> <p> There's no separate implementation; the only thing this method does is to delegate work to the <code>Select</code> method. It's literally the <code>Select</code> method, just with another name. </p> <p> Clearly, you could also have done it the other way around: implement <code>SelectSecond</code> and then call it from <code>Select</code>. </p> <p> The <code>SelectSecond</code> method works as you'd expect: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;t&nbsp;=&nbsp;<span style="color:#2b91af;">Tuple</span>.Create(<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;1337); <span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;t.SelectSecond(i&nbsp;=&gt;&nbsp;i&nbsp;%&nbsp;2&nbsp;==&nbsp;0);</pre> </p> <p> Again, <code>actual</code> is a tuple containing the values <code>"foo"</code> and <code>false</code>, because <code>1337</code> isn't even. </p> <p> This fits with the Haskell implementation, where <code>SelectSecond</code> is called <code>second</code>: </p> <p> <pre>Prelude Data.Bifunctor&gt; second even ("foo", 1337) ("foo",False)</pre> </p> <p> The result is still a pair where the first element is <code>"foo"</code> and the second element <code>False</code>, exactly like in the C# example. </p> <h3 id="17ce6b48946b4877924ddc5e3f841283"> Mapping both elements <a href="#17ce6b48946b4877924ddc5e3f841283" title="permalink">#</a> </h3> <p> With <code>SelectFirst</code> and <code>SelectSecond</code>, you can trivially implement <code>SelectBoth</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">U2</span>&gt;&nbsp;SelectBoth&lt;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">U1</span>,&nbsp;<span style="color:#2b91af;">U2</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Tuple</span>&lt;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">U1</span>&gt;&nbsp;source, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">T2</span>&gt;&nbsp;selector1, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">U1</span>,&nbsp;<span style="color:#2b91af;">U2</span>&gt;&nbsp;selector2) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;source.SelectFirst(selector1).SelectSecond(selector2); }</pre> </p> <p> This method takes two translations, <code>selector1</code> and <code>selector2</code>, and first uses <code>SelectFirst</code> to project along the first axis, and then <code>SelectSecond</code> to map the second dimension. </p> <p> This implementation creates an intermediary pair that callers never see, so this could theoretically be inefficient. In this article, however, I want to show you that it's possible to implement <code>SelectBoth</code> based on <code>SelectFirst</code> and <code>SelectSecond</code>. In the next article, you'll see how to do it the other way around. </p> <p> Using <code>SelectBoth</code> is easy: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;t&nbsp;=&nbsp;<span style="color:#2b91af;">Tuple</span>.Create(<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;42); <span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;t.SelectBoth(s&nbsp;=&gt;&nbsp;s.First(),&nbsp;i&nbsp;=&gt;&nbsp;i&nbsp;%&nbsp;2&nbsp;==&nbsp;0);</pre> </p> <p> This translation returns a pair where the first element is <code>'f'</code> and the second element is <code>true</code>. This is because the first lambda expression <code>s =&gt; s.First()</code> returns the first element of the input string <code>"foo"</code>, whereas the second lambda expression <code>i =&gt; i % 2 == 0</code> determines that <code>42</code> is even. </p> <p> In Haskell, <code>SelectBoth</code> is called <code>bimap</code>: </p> <p> <pre>Prelude Data.Bifunctor&gt; bimap head even ("foo", 42) ('f',True)</pre> </p> <p> The return value is consistent with the C# example, since the input is also equivalent. </p> <h3 id="93cde34382844098885a14a06aa03948"> Identity laws <a href="#93cde34382844098885a14a06aa03948" title="permalink">#</a> </h3> <p> Pairs obey all the bifunctor laws. While it's formal work to prove that this is the case, you can get an intuition for it via examples. Often, I use a property-based testing library like <a href="https://fscheck.github.io/FsCheck">FsCheck</a> or <a href="https://github.com/hedgehogqa/fsharp-hedgehog">Hedgehog</a> to demonstrate (not prove) that laws hold, but in this article, I'll keep it simple and only cover each law with a parametrised test. </p> <p> <pre><span style="color:blue;">private</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Id&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:#2b91af;">T</span>&nbsp;x)&nbsp;=&gt;&nbsp;x; [<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;42)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;bar&quot;</span>,&nbsp;1337)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foobar&quot;</span>,&nbsp;0)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;ploeh&quot;</span>,&nbsp;7)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;fnaah&quot;</span>,&nbsp;-6)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SelectFirstObeysFirstFunctorLaw(<span style="color:blue;">string</span>&nbsp;first,&nbsp;<span style="color:blue;">int</span>&nbsp;second) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;t&nbsp;=&nbsp;<span style="color:#2b91af;">Tuple</span>.Create(first,&nbsp;second); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(t,&nbsp;t.SelectFirst(Id)); }</pre> </p> <p> This test uses <a href="https://xunit.github.io">xUnit.net</a>'s <code>[Theory]</code> feature to supply a small set of example input values. It defines the identity function as a <code>private</code> function called <code>Id</code>, since C# doesn't come equipped with such a function in the Base Class Library. </p> <p> The test simply creates a tuple with the input values and verifies that the original tuple <code>t</code> is equal to the tuple projected over the first axis with the <code>Id</code> function. </p> <p> Likewise, the first functor law applies when translating over the second dimension: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;42)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;bar&quot;</span>,&nbsp;1337)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foobar&quot;</span>,&nbsp;0)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;ploeh&quot;</span>,&nbsp;7)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;fnaah&quot;</span>,&nbsp;-6)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SelectSecondObeysFirstFunctorLaw(<span style="color:blue;">string</span>&nbsp;first,&nbsp;<span style="color:blue;">int</span>&nbsp;second) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;t&nbsp;=&nbsp;<span style="color:#2b91af;">Tuple</span>.Create(first,&nbsp;second); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(t,&nbsp;t.SelectSecond(Id)); }</pre> </p> <p> This is the same test as the previous test, with the only exception that it calls <code>SelectSecond</code> instead of <code>SelectFirst</code>. </p> <p> Since <code>SelectBoth</code> in this example is implemented by composing <code>SelectFirst</code> and <code>SelectSecond</code>, you should expect it to obey the general identity law for bifunctors. It does, but it's always nice to see it with your own eyes: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;42)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;bar&quot;</span>,&nbsp;1337)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foobar&quot;</span>,&nbsp;0)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;ploeh&quot;</span>,&nbsp;7)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;fnaah&quot;</span>,&nbsp;-6)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SelectBothObeysIdentityLaw(<span style="color:blue;">string</span>&nbsp;first,&nbsp;<span style="color:blue;">int</span>&nbsp;second) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;t&nbsp;=&nbsp;<span style="color:#2b91af;">Tuple</span>.Create(first,&nbsp;second); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(t,&nbsp;t.SelectBoth(Id,&nbsp;Id)); }</pre> </p> <p> Here you can see that projecting over both dimensions with the identity function returns the original tuple. </p> <h3 id="6bd839540b9646db9acfe25b0227b241"> Consistency law <a href="#6bd839540b9646db9acfe25b0227b241" title="permalink">#</a> </h3> <p> In general, it shouldn't matter whether you map with <code>SelectBoth</code> or a combination of <code>SelectFirst</code> and <code>SelectSecond</code>: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;42)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;bar&quot;</span>,&nbsp;1337)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foobar&quot;</span>,&nbsp;0)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;ploeh&quot;</span>,&nbsp;7)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;ConsistencyLawHolds(<span style="color:blue;">string</span>&nbsp;first,&nbsp;<span style="color:blue;">int</span>&nbsp;second) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">bool</span>&gt;&nbsp;f&nbsp;=&nbsp;<span style="color:blue;">string</span>.IsNullOrWhiteSpace; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:#2b91af;">DateTime</span>&gt;&nbsp;g&nbsp;=&nbsp;i&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">DateTime</span>(i); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;t&nbsp;=&nbsp;<span style="color:#2b91af;">Tuple</span>.Create(first,&nbsp;second); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.SelectBoth(f,&nbsp;g),&nbsp;t.SelectSecond(g).SelectFirst(f)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.SelectFirst(f).SelectSecond(g), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.SelectSecond(g).SelectFirst(f)); }</pre> </p> <p> This example creates two functions <code>f</code> and <code>g</code>. The first function, <code>f</code>, is just an alias for <code>string.IsNullOrWhiteSpace</code>, although I want to stress that it's just an example. The law should hold for any two (<a href="https://en.wikipedia.org/wiki/Pure_function">pure</a>) functions. The second function, <code>g</code>, creates a new <code>DateTime</code> object from an integer, using one of the <code>DateTime</code> constructor overloads. </p> <p> The test then verifies that you get the same result from calling <code>SelectBoth</code> as when you call <code>SelectFirst</code> followed by <code>SelectSecond</code>, or the other way around. </p> <h3 id="866a68ce5f3e4513882409498e743bb3"> Composition laws <a href="#866a68ce5f3e4513882409498e743bb3" title="permalink">#</a> </h3> <p> The composition laws insist that you can compose functions, or translations, and that again, the choice to do one or the other doesn't matter. Along each of the axes, it's just the second functor law applied. You've already seen that <code>SelectSecond</code> is nothing but an alias for <code>Select</code>, so surely, the second functor law must hold for <code>SelectSecond</code> as well. This parametrised test demonstrates that it does: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;42)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;bar&quot;</span>,&nbsp;1337)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foobar&quot;</span>,&nbsp;0)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;ploeh&quot;</span>,&nbsp;7)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;fnaah&quot;</span>,&nbsp;-6)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SecondFunctorLawHoldsForSelectSecond(<span style="color:blue;">string</span>&nbsp;first,&nbsp;<span style="color:blue;">int</span>&nbsp;second) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">bool</span>,&nbsp;<span style="color:blue;">char</span>&gt;&nbsp;f&nbsp;=&nbsp;b&nbsp;=&gt;&nbsp;b&nbsp;?&nbsp;<span style="color:#a31515;">&#39;T&#39;</span>&nbsp;:&nbsp;<span style="color:#a31515;">&#39;F&#39;</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">bool</span>&gt;&nbsp;g&nbsp;=&nbsp;i&nbsp;=&gt;&nbsp;i&nbsp;%&nbsp;2&nbsp;==&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;t&nbsp;=&nbsp;<span style="color:#2b91af;">Tuple</span>.Create(first,&nbsp;second); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.SelectSecond(x&nbsp;=&gt;&nbsp;f(g(x))), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.SelectSecond(g).SelectSecond(f)); }</pre> </p> <p> Here, <code>f</code> is a function that returns <code>'T'</code> for <code>true</code> and <code>'F'</code> for <code>false</code>, and <code>g</code> is a function that, as you've seen before, determines whether a number is even. The second functor law states that mapping <code>f(g(x))</code> in a single step is equivalent to first mapping over <code>g</code> and then map the result of that using <code>f</code>. </p> <p> The same law applies if you fix the second dimension and translate over the first: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;42)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;bar&quot;</span>,&nbsp;1337)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foobar&quot;</span>,&nbsp;0)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;ploeh&quot;</span>,&nbsp;7)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;fnaah&quot;</span>,&nbsp;-6)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SecondFunctorLawHoldsForSelectFirst(<span style="color:blue;">string</span>&nbsp;first,&nbsp;<span style="color:blue;">int</span>&nbsp;second) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">bool</span>&gt;&nbsp;f&nbsp;=&nbsp;x&nbsp;=&gt;&nbsp;x&nbsp;%&nbsp;2&nbsp;==&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;g&nbsp;=&nbsp;s&nbsp;=&gt;&nbsp;s.Length; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;t&nbsp;=&nbsp;<span style="color:#2b91af;">Tuple</span>.Create(first,&nbsp;second); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.SelectFirst(x&nbsp;=&gt;&nbsp;f(g(x))), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.SelectFirst(g).SelectFirst(f)); }</pre> </p> <p> Here, <code>f</code> is the <em>even</em> function, whereas <code>g</code> is a function that returns the length of a string. Again, the test demonstrates that the output is the same whether you map over an intermediary step, or whether you map using only a single step. </p> <p> This generalises to the composition law for <code>SelectBoth</code>: </p> <p> <pre>[<span style="color:#2b91af;">Theory</span>] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;42)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;bar&quot;</span>,&nbsp;1337)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;foobar&quot;</span>,&nbsp;0)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;ploeh&quot;</span>,&nbsp;7)] [<span style="color:#2b91af;">InlineData</span>(<span style="color:#a31515;">&quot;fnaah&quot;</span>,&nbsp;-6)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SelectBothCompositionLawHolds(<span style="color:blue;">string</span>&nbsp;first,&nbsp;<span style="color:blue;">int</span>&nbsp;second) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">bool</span>&gt;&nbsp;f&nbsp;=&nbsp;x&nbsp;=&gt;&nbsp;x&nbsp;%&nbsp;2&nbsp;==&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;g&nbsp;=&nbsp;s&nbsp;=&gt;&nbsp;s.Length; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">bool</span>,&nbsp;<span style="color:blue;">char</span>&gt;&nbsp;h&nbsp;=&nbsp;b&nbsp;=&gt;&nbsp;b&nbsp;?&nbsp;<span style="color:#a31515;">&#39;T&#39;</span>&nbsp;:&nbsp;<span style="color:#a31515;">&#39;F&#39;</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">bool</span>&gt;&nbsp;i&nbsp;=&nbsp;x&nbsp;=&gt;&nbsp;x&nbsp;%&nbsp;2&nbsp;==&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;t&nbsp;=&nbsp;<span style="color:#2b91af;">Tuple</span>.Create(first,&nbsp;second); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.SelectBoth(x&nbsp;=&gt;&nbsp;f(g(x)),&nbsp;y&nbsp;=&gt;&nbsp;h(i(y))), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.SelectBoth(g,&nbsp;i).SelectBoth(f,&nbsp;h)); }</pre> </p> <p> Again, whether you translate in one or two steps shouldn't affect the outcome. </p> <p> As all of these tests demonstrate, the bifunctor laws hold for pairs. The tests only showcase 4-5 examples for a pair of string and integer, but I hope it gives you an intuition how any pair is a bifunctor. After all, the <code>SelectFirst</code>, <code>SelectSecond</code>, and <code>SelectBoth</code> methods are all generic, and they behave the same for all generic type arguments. </p> <h3 id="dfd4aa6edc66462c9d02d46ce44b1bda"> Summary <a href="#dfd4aa6edc66462c9d02d46ce44b1bda" title="permalink">#</a> </h3> <p> Pairs (two-tuples) are bifunctors. You can translate the first and second element of a pair independently of each other, and the bifunctor laws hold for any pure translation, no matter how you compose the projections. </p> <p> As always, there can be performance differences between the various compositions, but the outputs will be the same regardless of composition. </p> <p> A functor, and by extension, a bifunctor, is a structure-preserving map. This means that any projection preserves the structure of the underlying container. In practice that means that for pairs, no matter how you translate a pair, it remains a pair. A pair is characterised by containing two values at once, and no matter how you translate it, it'll still contain two values. </p> <p> The other common bifunctor, Either, is complementary. While it has two dimensions, it only contains one value, which is of either the one type or the other. It's still a bifunctor, though, because mappings preserve the structure of Either, too. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2019/01/07/either-bifunctor">Either bifunctor</a>. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="http://blog.ploeh.dk/support">supporting it</a>. Bifunctors http://blog.ploeh.dk/2018/12/24/bifunctors 2018-12-24T14:40:00+00:00 Mark Seemann <div id="post"> <p> <em>Bifunctors are like functors, only they vary in two dimensions instead of one. An article for object-oriented programmers.</em> </p> <p> This article is a continuation of <a href="http://blog.ploeh.dk/2018/03/22/functors">the article series about functors</a> and about <a href="http://blog.ploeh.dk/2018/10/01/applicative-functors">applicative functors</a>. In this article, you'll learn about a generalisation called a <em>bifunctor</em>. The prefix <em>bi</em> typically indicates that there's <em>two</em> of something, and that's also the case here. </p> <p> As you've already seen in the functor articles, a functor is a mappable <a href="https://bartoszmilewski.com/2014/01/14/functors-are-containers">container</a> of generic values, like <code>Foo&lt;T&gt;</code>, where the type of the contained value(s) can be any generic type <code>T</code>. A bifunctor is just a container with two independent generic types, like <code>Bar&lt;T, U&gt;</code>. If you can map each of the types independently of the other, you may have a bifunctor. </p> <p> The two most common bifunctors are tuples and Either. </p> <h3 id="c8062c28a0ed471a8995bee180d14aa6"> Maps <a href="#c8062c28a0ed471a8995bee180d14aa6" title="permalink">#</a> </h3> <p> A normal functor is based on a structure-preserving map of the contents within a container. You can, for example, translate an <code>IEnumerable&lt;int&gt;</code> to an <code>IEnumerable&lt;string&gt;</code>, or a <code>Maybe&lt;DateTime&gt;</code> to a <code>Maybe&lt;bool&gt;</code>. The axis of variability is the generic type argument <code>T</code>. You can translate <code>T1</code> to <code>T2</code> inside a container, but the type of the container remains the same: you can translate <code>Tree&lt;T1&gt;</code> to <code>Tree&lt;T2&gt;</code>, but it remains a <code>Tree&lt;&gt;</code>. </p> <p> <img src="/content/binary/monofunctors.png" alt="Three translations: IEnumerable, Maybe, and Tree."> </p> <p> A bifunctor involves a pair of maps, one for each generic type. You can map a <code>Bar&lt;string, int&gt;</code> to a <code>Bar&lt;bool, int&gt;</code>, or to a <code>Bar&lt;string, DateTime&gt;</code>, or even to a <code>Bar&lt;bool, DateTime&gt;</code>. Notice that the last example, mapping from <code>Bar&lt;string, int&gt;</code> to <code>Bar&lt;bool, DateTime&gt;</code> could be viewed as translating both axes simultaneously. </p> <p> <img src="/content/binary/bifunctor.png" alt="Bifunctor diagram."> </p> <p> In <a href="https://www.haskell.org">Haskell</a>, the two maps are called <code>first</code> and <code>second</code>, while the 'simultaneous' map is called <code>bimap</code>. </p> <p> The <code>first</code> translation translates the first, or left-most, value in the container. You can use it to map <code>Bar&lt;string, int&gt;</code> to a <code>Bar&lt;bool, int&gt;</code>. In C#, we could decide to call the method <code>SelectFirst</code>, or <code>SelectLeft</code>, in order to align with the C# naming convention of calling the functor morphism <code>Select</code>. </p> <p> Likewise, the <code>second</code> map translates the second, or right-most, value in the container. This is where you map <code>Bar&lt;string, int&gt;</code> to <code>Bar&lt;string, DateTime&gt;</code>. In C#, we could call the method <code>SelectSecond</code>, or <code>SelectRight</code>. </p> <p> The <code>bimap</code> function maps both values in the container in one go. This corresponds to a translation from <code>Bar&lt;string, int&gt;</code> to <code>Bar&lt;bool, DateTime&gt;</code>. In C#, we could call the method <code>SelectBoth</code>. There's no established naming conventions for bifunctors in C# that I know of, so these names are just some that I made up. </p> <p> You'll see examples of how to implement and use such functions in the next articles: <ul> <li><a href="http://blog.ploeh.dk/2018/12/31/tuple-bifunctor">Tuple bifunctor</a></li> <li><a href="http://blog.ploeh.dk/2019/01/07/either-bifunctor">Either bifunctor</a></li> </ul> Other bifunctors exist, but those two are the most common. </p> <h3 id="838097e59afd4555b989594b62082f39"> Identity laws <a href="#838097e59afd4555b989594b62082f39" title="permalink">#</a> </h3> <p> As is the case with functors, laws govern bifunctors. Some of the functor laws carry over, but are simply repeated over both axes, while other laws are generalisations of the functor laws. For example, the first functor law states that if you translate a container with the identity function, the result is the original input. This generalises to bifunctors as well: </p> <p> <pre>bimap id id ≡ id</pre> </p> <p> This just states that if you translate both axes using the <a href="http://blog.ploeh.dk/2017/11/13/endomorphism-monoid">endomorphic</a> Identity, it's equivalent to applying the Identity. </p> <p> <img src="/content/binary/bimap-id-id-bifunctor-law.png" alt="The bifunctor law for applying id to both axes simultaneously."> </p> <p> Using C# syntax, you could express the law like this: </p> <p> <pre>bf.SelectBoth(id,&nbsp;id)&nbsp;==&nbsp;bf;</pre> </p> <p> Here, <code>bf</code> is some bifunctor, and <code>id</code> is the identity function. The point is that if you translate over both axes, but actually don't perform a real translation, nothing happens. </p> <p> Likewise, if you consider a bifunctor a functor over two dimensions, the first functor law should hold for both: </p> <p> <pre>first id ≡ id second id ≡ id</pre> </p> <p> Both of those equalities only restate the first functor law for each dimension. If you map an axis with the identity function, nothing happens: </p> <p> <img src="/content/binary/first-id-second-id-bifunctor-laws.png" alt="The first functor law applied to both dimensions of a bifunctor."> </p> <p> In C#, you can express both laws like this: </p> <p> <pre>bf.SelectFirst(id)&nbsp;==&nbsp;bf; bf.SelectSecond(id)&nbsp;==&nbsp;bf;</pre> </p> <p> When calling <code>SelectFirst</code>, you translate only the first axis while you keep the second axis constant. When calling <code>SelectSecond</code> it's the other way around: you translate only the second axis while keeping the first axis constant. In both cases, though, if you use the identity function for the translation, you effectively keep the mapped dimension constant as well. Therefore, one would expect the result to be the same as the input. </p> <h3 id="57cfa8fd78084e8ca19d073d856a8c8a"> Consistency law <a href="#57cfa8fd78084e8ca19d073d856a8c8a" title="permalink">#</a> </h3> <p> As you'll see in the articles on tuple and Either bifunctors, you can derive <code>bimap</code> or <code>SelectBoth</code> from <code>first</code>/<code>SelectFirst</code> and <code>second</code>/<code>SelectSecond</code>, or the other way around. If, however, you decide to implement all three functions, they must act in a consistent manner. The name <em>Consistency law</em>, however, is entirely my own invention. If it has a more well-known name, I'm not aware of it. </p> <p> In pseudo-Haskell syntax, you can express the law like this: </p> <p> <pre>bimap f g ≡ first f . second g</pre> </p> <p> This states that mapping (using the functions <code>f</code> and <code>g</code>) simultaneously should produce the same result as mapping using an intermediary step: </p> <p> <img src="/content/binary/bifunctor-consistency-law.png" alt="The bifunctor Consistency law."> </p> <p> In C#, you could express it like this: </p> <p> <pre>bf.SelectBoth(f,&nbsp;g)&nbsp;==&nbsp;bf.SelectSecond(g).SelectFirst(f);</pre> </p> <p> You can project the input bifunctor <code>bf</code> using both <code>f</code> and <code>g</code> in a single step, or you can first translate the second dimension with <code>g</code> and then subsequently map that intermediary result along the first axis with <code>f</code>. </p> <p> The above diagram ought to commute: </p> <p> <img src="/content/binary/bifunctor-consistency-commutativity-law.png" alt="The bifunctor Consistency law."> </p> <p> It shouldn't matter whether the intermediary step is applying <code>f</code> along the first axis or <code>g</code> along the second axis. In C#, we can write it like this: </p> <p> <pre>bf.SelectFirst(f).SelectSecond(g)&nbsp;==&nbsp;bf.SelectSecond(g).SelectFirst(f);</pre> </p> <p> On the left-hand side, you first translate the bifunctor <code>bf</code> along the first axis, using <code>f</code>, and then translate that intermediary result along the second axis, using <code>g</code>. On the right-hand side, you first project <code>bf</code> along the second axis, using <code>g</code>, and then map that intermediary result over the first dimension, using <code>f</code>. </p> <p> Regardless of order of translation, the result should be the same. </p> <h3 id="a1d12a9d1afe428684b3d693a39cb5d1"> Composition laws <a href="#a1d12a9d1afe428684b3d693a39cb5d1" title="permalink">#</a> </h3> <p> Similar to how the first functor law generalises to bifunctors, the second functor law generalises as well. For (mono)functors, the second functor law states that if you have two functions over the same dimension, it shouldn't matter whether you perform a projection in one, composed step, or in two steps with an intermediary result. </p> <p> For bifunctors, you can generalise that law and state that you can project over both dimensions in one or two steps: </p> <p> <pre>bimap (f . g) (h . i) ≡ bimap f h . bimap g i</pre> </p> <p> If you have two functions, <code>f</code> and <code>g</code>, that compose, and two other functions, <code>h</code> and <code>i</code>, that also compose, you can translate in either one or two steps; the result should be the same. </p> <p> <img src="/content/binary/bimap-composition-law.png" alt="The bifunctor composition law."> </p> <p> In C#, you can express the law like this: </p> <p> <pre>bf.SelectBoth(x&nbsp;=&gt;&nbsp;f(g(x)),&nbsp;y&nbsp;=&gt;&nbsp;h(i(y)))&nbsp;==&nbsp;bf.SelectBoth(g,&nbsp;i).SelectBoth(f,&nbsp;h);</pre> </p> <p> On the left-hand side, the first dimension is translated in one step. For each <code>x</code> contained in <code>bf</code>, the translation first invokes <code>g(x)</code>, and then immediately calls <code>f</code> with the output of <code>g(x)</code>. The second dimension also gets translated in one step. For each <code>y</code> contained in <code>bf</code>, the translation first invokes <code>i(y)</code>, and then immediately calls <code>h</code> with the output of <code>i(y)</code>. </p> <p> On the right-hand side, you first translate <code>bf</code> along both axes using <code>g</code> and <code>i</code>. This produces an intermediary result that you can use as input for a second translation with <code>f</code> and <code>h</code>. </p> <p> The translation on the left-hand side should produce the same output as the right-hand side. </p> <p> Finally, if you keep one of the dimensions fixed, you essentially have a normal functor, and the second functor law should still hold. For example, if you hold the second dimension fixed, translating over the first dimension is equivalent to a normal functor projection, so the second functor law should hold: </p> <p> <pre>first (f . g) ≡ first f . first g</pre> </p> <p> If you replace <code>first</code> with <code>fmap</code>, you have the second functor law. </p> <p> <img src="/content/binary/second-functor-law-over-first-bifunctor-dimension.png" alt="The second functor law applied to the first dimension of a bifunctor."> </p> <p> In C#, you can write it like this: </p> <p> <pre>bf.SelectFirst(x&nbsp;=&gt;&nbsp;f(g(x)))&nbsp;==&nbsp;bf.SelectFirst(g).SelectFirst(f);</pre> </p> <p> Likewise, you can keep the first dimension constant and apply the second functor law to projections along the second axis: </p> <p> <pre>second (f . g) ≡ second f . second g</pre> </p> <p> Again, if you replace <code>second</code> with <code>fmap</code>, you have the second functor law. </p> <p> <img src="/content/binary/second-functor-law-over-second-bifunctor-dimension.png" alt="The second functor law applied to the second dimension of a bifunctor."> </p> <p> In C#, you express it like this: </p> <p> <pre>bf.SelectSecond(x&nbsp;=&gt;&nbsp;f(g(x)))&nbsp;==&nbsp;bf.SelectSecond(g).SelectSecond(f);</pre> </p> <p> The last two of these composition laws are specialisations of the general composition law, but where you fix either one or the other dimension. </p> <h3 id="41120f4d6ead482f9254a62853d9e1c4"> Summary <a href="#41120f4d6ead482f9254a62853d9e1c4" title="permalink">#</a> </h3> <p> A bifunctor is a container that can be translated over two dimensions, instead of a (mono)functor, which is a container that can be translated over a single dimension. In reality, there isn't a multitude of different bifunctors. While others exist, tuples and Either are the two most common bifunctors. They share an abstraction, but are still fundamentally different. A tuple always contains values of both dimensions at the same time, whereas Either only contains one of the values. </p> <p> Do trifunctors, quadfunctors, and so on, exist? Nothing prevents that, but they aren't particularly useful; in practice, you never run into them. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/12/31/tuple-bifunctor">Tuple bifunctor</a>. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="http://blog.ploeh.dk/support">supporting it</a>. The Lazy applicative functor http://blog.ploeh.dk/2018/12/17/the-lazy-applicative-functor 2018-12-17T07:52:00+00:00 Mark Seemann <div id="post"> <p> <em>Lazy computations form an applicative functor.</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>. A previous article has described how <a href="http://blog.ploeh.dk/2018/09/10/the-lazy-functor">lazy computations form a functor</a>. In this article, you'll see that lazy computations also form an applicative functor. </p> <h3 id="c04ca371d39847cc86a90240a7f53745"> Apply <a href="#c04ca371d39847cc86a90240a7f53745" title="permalink">#</a> </h3> <p> As you have <a href="http://blog.ploeh.dk/2018/10/15/an-applicative-password-list">previously seen</a>, C# isn't the best fit for the concept of applicative functors. Nevertheless, you can write an <code>Apply</code> extension method following the applicative 'code template': </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;Apply&lt;<span style="color:#2b91af;">TResult</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;<span style="color:#2b91af;">Lazy</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;">Lazy</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;source) { &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.Value(source.Value)); }</pre> </p> <p> The <code>Apply</code> method takes both a lazy <code>selector</code> and a lazy value called <code>source</code>. It applies the function to the value and returns the result, still as a lazy value. If you have a lazy function <code>f</code> and a lazy value <code>x</code>, you can use the method like this: </p> <p> <pre><span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">string</span>&gt;&gt;&nbsp;f&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <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;f.Apply(x);</pre> </p> <p> The utility of <code>Apply</code>, however, mostly tends to emerge when you need to chain multiple <a href="https://bartoszmilewski.com/2014/01/14/functors-are-containers">containers</a> together; in this case, multiple lazy values. You can do that by adding as many overloads to <code>Apply</code> as you need: </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;">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;">Lazy</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;">Lazy</span>&lt;<span style="color:#2b91af;">T1</span>&gt;&nbsp;source) { &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;">Func</span>&lt;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;(()&nbsp;=&gt;&nbsp;y&nbsp;=&gt;&nbsp;selector.Value(source.Value,&nbsp;y)); }</pre> </p> <p> This overload partially applies the input function. When <code>selector</code> is a function that takes two arguments, you can apply a single of those two arguments, and the result is a new function that closes over the value, but still waits for its second input argument. You can use it like this: </p> <p> <pre><span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">char</span>,&nbsp;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">string</span>&gt;&gt;&nbsp;f&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">char</span>&gt;&nbsp;c&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;i&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;s&nbsp;=&nbsp;f.Apply(c).Apply(i);</pre> </p> <p> Notice that you can chain the various overloads of <code>Apply</code>. In the above example, you have a lazy function that takes a <code>char</code> and an <code>int</code> as input, and returns a <code>string</code>. It could, for instance, be a function that invokes <a href="https://docs.microsoft.com/en-us/dotnet/api/system.string.-ctor?view=netframework-4.7.2#System_String__ctor_System_Char_System_Int32_">the equivalent <code>string</code> constructor overload</a>. </p> <p> Calling <code>f.Apply(c)</code> uses the overload that takes a <code>Lazy&lt;Func&lt;T1, T2, TResult&gt;&gt;</code> as input. The return value is a <code>Lazy&lt;Func&lt;int, string&gt;&gt;</code>, which the first <code>Apply</code> then picks up, to return a <code>Lazy&lt;string&gt;</code>. </p> <p> Usually, you may have one, two, or several lazy values, whereas your function itself isn't contained in a <code>Lazy</code> container. While you can use a helper method such as <code>Lazy.FromValue</code> to 'elevate' a 'normal' function to a lazy function value, it's often more convenient if you have another <code>Apply</code> overload 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;">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;">Func</span>&lt;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;selector, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">T1</span>&gt;&nbsp;source) { &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;">Func</span>&lt;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&gt;(()&nbsp;=&gt;&nbsp;y&nbsp;=&gt;&nbsp;selector(source.Value,&nbsp;y)); }</pre> </p> <p> The only difference to the equivalent overload is that in this overload, <code>selector</code> isn't a <code>Lazy</code> value, while <code>source</code> still is. This simplifies usage: </p> <p> <pre><span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">char</span>,&nbsp;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;f&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">char</span>&gt;&nbsp;c&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;i&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;s&nbsp;=&nbsp;f.Apply(c).Apply(i);</pre> </p> <p> Notice that in this variation of the example, <code>f</code> is no longer a <code>Lazy&lt;Func&lt;...&gt;&gt;</code>, but just a normal <code>Func</code>. </p> <h3 id="966d763816c84c839b7704cdebfd7bac"> F# <a href="#966d763816c84c839b7704cdebfd7bac" title="permalink">#</a> </h3> <p> <a href="https://fsharp.org">F#</a>'s type inference is more powerful than C#'s, so you don't have to resort to various overloads to make things work. You could, for example, create a minimal <code>Lazy</code> module: </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 &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;Lazy&lt;(&#39;a&nbsp;-&gt;&nbsp;&#39;b)&gt;&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;apply&nbsp;(x&nbsp;:&nbsp;Lazy&lt;_&gt;)&nbsp;(f&nbsp;:&nbsp;Lazy&lt;_&gt;)&nbsp;=&nbsp;<span style="color:blue;">lazy</span>&nbsp;f.Value&nbsp;x.Value</pre> </p> <p> In this code listing, I've repeated the <code>map</code> function shown in a <a href="http://blog.ploeh.dk/2018/09/10/the-lazy-functor">previous article</a>. It's not required for the implementation of <code>apply</code>, but you'll see it in use shortly, so I thought it was convenient to include it in the listing. </p> <p> If you belong to the camp of F# programmers who think that F# should emulate <a href="https://www.haskell.org">Haskell</a>, you can also introduce an operator: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;(&lt;*&gt;)&nbsp;f&nbsp;x&nbsp;=&nbsp;Lazy.apply&nbsp;x&nbsp;f</pre> </p> <p> Notice that this <code>&lt;*&gt;</code> operator simply flips the arguments of <code>Lazy.apply</code>. If you introduce such an operator, be aware that the admonition from <a href="http://blog.ploeh.dk/2018/10/01/applicative-functors">the overview article</a> still applies. In Haskell, the <code>&lt;*&gt;</code> operator applies to any <code>Applicative</code>, which makes it truly general. In F#, once you define an operator like this, it applies specifically to a particular container type, which, in this case, is <code>Lazy&lt;'a&gt;</code>. </p> <p> You can replicate the first of the above C# examples like this: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;f&nbsp;:&nbsp;Lazy&lt;int&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;string&gt;&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:blue;">let</span>&nbsp;x&nbsp;:&nbsp;Lazy&lt;int&gt;&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:blue;">let</span>&nbsp;y&nbsp;:&nbsp;Lazy&lt;string&gt;&nbsp;=&nbsp;Lazy.apply&nbsp;x&nbsp;f</pre> </p> <p> Alternatively, if you want to use the <code>&lt;*&gt;</code> operator, you can compute <code>y</code> like this: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;y&nbsp;:&nbsp;Lazy&lt;string&gt;&nbsp;=&nbsp;f&nbsp;&lt;*&gt;&nbsp;x</pre> </p> <p> Chaining multiple lazy computations together also works: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;f&nbsp;:&nbsp;Lazy&lt;char&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;int&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;string&gt;&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:blue;">let</span>&nbsp;c&nbsp;:&nbsp;Lazy&lt;char&gt;&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:blue;">let</span>&nbsp;i&nbsp;:&nbsp;Lazy&lt;int&gt;&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:blue;">let</span>&nbsp;s&nbsp;=&nbsp;Lazy.apply&nbsp;c&nbsp;f&nbsp;|&gt;&nbsp;Lazy.apply&nbsp;i</pre> </p> <p> Again, you can compute <code>s</code> with the operator, if that's more to your liking: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;s&nbsp;:&nbsp;Lazy&lt;string&gt;&nbsp;=&nbsp;f&nbsp;&lt;*&gt;&nbsp;c&nbsp;&lt;*&gt;&nbsp;i</pre> </p> <p> Finally, if your function isn't contained in a <code>Lazy</code> value, you can start out with <code>Lazy.map</code>: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;f&nbsp;:&nbsp;char&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;int&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;string&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:blue;">let</span>&nbsp;c&nbsp;:&nbsp;Lazy&lt;char&gt;&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:blue;">let</span>&nbsp;i&nbsp;:&nbsp;Lazy&lt;int&gt;&nbsp;=&nbsp;<span style="color:green;">//&nbsp;...</span> <span style="color:blue;">let</span>&nbsp;s&nbsp;:&nbsp;Lazy&lt;string&gt;&nbsp;=&nbsp;Lazy.map&nbsp;f&nbsp;c&nbsp;|&gt;&nbsp;Lazy.apply&nbsp;i</pre> </p> <p> This works without requiring additional overloads. Since F# natively supports partial function application, the first step in the pipeline, <code>Lazy.map f c</code> has the type <code>Lazy&lt;int -&gt; string&gt;</code> because <code>f</code> is a function of the type <code>char -&gt; int -&gt; string</code>, but in the first step, <code>Lazy.map f c</code> only supplies <code>c</code>, which contains a <code>char</code> value. </p> <p> Once more, if you prefer the infix operator, you can also compute <code>s</code> as: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;s&nbsp;:&nbsp;Lazy&lt;string&gt;&nbsp;=&nbsp;<span style="color:blue;">lazy</span>&nbsp;f&nbsp;&lt;*&gt;&nbsp;c&nbsp;&lt;*&gt;&nbsp;i</pre> </p> <p> While I find <a href="http://blog.ploeh.dk/2018/07/02/terse-operators-make-business-code-more-readable">operator-based syntax attractive in Haskell code</a>, I'm more hesitant about such syntax in F#. </p> <h3 id="63a6579eeb644627b02efc3f9aabd202"> Haskell <a href="#63a6579eeb644627b02efc3f9aabd202" title="permalink">#</a> </h3> <p> As outlined in the <a href="http://blog.ploeh.dk/2018/09/10/the-lazy-functor">previous article</a>, Haskell is already lazily evaluated, so it makes little sense to introduce an explicit <code>Lazy</code> data container. While Haskell's built-in <code>Identity</code> isn't quite equivalent to .NET's <code>Lazy&lt;T&gt;</code> object, some similarities remain; most notably, the <a href="http://blog.ploeh.dk/2018/09/03/the-identity-functor">Identity functor</a> is also applicative: </p> <p> <pre>Prelude Data.Functor.Identity&gt; :t f f :: a -&gt; Int -&gt; [a] Prelude Data.Functor.Identity&gt; :t c c :: Identity Char Prelude Data.Functor.Identity&gt; :t i i :: Num a =&gt; Identity a Prelude Data.Functor.Identity&gt; :t f &lt;$&gt; c &lt;*&gt; i f &lt;$&gt; c &lt;*&gt; i :: Identity String</pre> </p> <p> This little GHCi session simply illustrates that if you have a 'normal' function <code>f</code> and two <code>Identity</code> values <code>c</code> and <code>i</code>, you can compose them using the infix <em>map</em> operator <code>&lt;$&gt;</code>, followed by the infix <em>apply</em> operator <code>&lt;*&gt;</code>. This is equivalent to the F# expression <code>Lazy.map f c |&gt; Lazy.apply i</code>. </p> <p> Still, this makes little sense, since all Haskell expressions are already lazily evaluated. </p> <h3 id="d3ddcafbb8e14bfea2c18828cf44f244"> Summary <a href="#d3ddcafbb8e14bfea2c18828cf44f244" title="permalink">#</a> </h3> <p> The Lazy functor is also an <em>applicative functor</em>. This can be used to combine multiple lazily computed values into a single lazily computed value. </p> <p> <strong>Next:</strong> <a href="http://blog.ploeh.dk/2018/12/24/bifunctors">Bifunctors</a>. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="http://blog.ploeh.dk/support">supporting it</a>. Danish CPR numbers in F# http://blog.ploeh.dk/2018/12/10/danish-cpr-numbers-in-f 2018-12-10T08:14:00+00:00 Mark Seemann <div id="post"> <p> <em>An example of domain-modelling in F#, including a fine example of using the option type as an applicative functor.</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>, although the applicative functor example doesn't appear until towards the end. This article also serves the purpose of showing an example of <a href="http://amzn.to/WBCwx7">Domain-Driven Design</a> in F#. </p> <h3 id="163a2e2ecb144172a974d1eb23ff6703"> Danish personal identification numbers <a href="#163a2e2ecb144172a974d1eb23ff6703" title="permalink">#</a> </h3> <p> As outlined in the <a href="http://blog.ploeh.dk/2018/11/26/the-test-data-generator-applicative-functor">previous article</a>, in Denmark, everyone has a <a href="https://en.wikipedia.org/wiki/Personal_identification_number_(Denmark)">personal identification number</a>, in Danish called <em>CPR-nummer</em> (<em>CPR number</em>). </p> <p> CPR numbers have a simple format: <code>DDMMYY-SSSS</code>, where the first six digits indicate a person's birth date, and the last four digits are a sequence number. Some information, however, is also embedded in the sequence number. An example could be <code>010203-1234</code>, which indicates a woman born February 1, 1903. </p> <p> One way to model this in <a href="https://fsharp.org">F#</a> is with a single-case discriminated union: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;<span style="color:teal;">CprNumber</span>&nbsp;=&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:navy;">CprNumber</span>&nbsp;<span style="color:blue;">of</span>&nbsp;(<span style="color:teal;">int</span>&nbsp;*&nbsp;<span style="color:teal;">int</span>&nbsp;*&nbsp;<span style="color:teal;">int</span>&nbsp;*&nbsp;<span style="color:teal;">int</span>)&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">override</span>&nbsp;x.<span style="color:navy;">ToString</span>&nbsp;()&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;(<span style="color:navy;">CprNumber</span>&nbsp;(day,&nbsp;month,&nbsp;year,&nbsp;sequenceNumber))&nbsp;=&nbsp;x &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:navy;">sprintf</span>&nbsp;<span style="color:#a31515;">&quot;</span><span style="color:teal;">%02d%02d%02d</span><span style="color:#a31515;">-</span><span style="color:teal;">%04d</span><span style="color:#a31515;">&quot;</span>&nbsp;day&nbsp;month&nbsp;year&nbsp;sequenceNumber</pre> </p> <p> This is a common idiom in F#. In object-oriented design with e.g. C# or Java, you'd typically create a class and put guard clauses in its constructor. This would prevent a user from initialising an object with invalid data (such as <code>401500-1234</code>). While you <em>can</em> create classes in F# as well, a single-case union with a private case constructor can achieve the same degree of encapsulation. </p> <p> In this case, I decided to use a quadruple (4-tuple) as the internal representation, but this isn't visible to users. This gives me the option to refactor the internal representation, if I need to, without breaking existing clients. </p> <h3 id="83eaa41329eb4d8b894e0640f600f110"> Creating CPR number values <a href="#83eaa41329eb4d8b894e0640f600f110" title="permalink">#</a> </h3> <p> Since the <code>CprNumber</code> case constructor is private, you can't just create new values like this: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;<span style="color:#9b9b9b;">cpr</span>&nbsp;=&nbsp;CprNumber&nbsp;(1,&nbsp;1,&nbsp;1,&nbsp;1118) </pre> </p> <p> If you're outside the <code>Cpr</code> module that defines the type, this <strong>doesn't compile</strong>. This is by design, but obviously you need a way to create values. For convenience, input values for day, month, and so on, are represented as <code>int</code>s, which can be zero, negative, or way too large for CPR numbers. There's no way to statically guarantee that you can create a value, so you'll have to settle for a <code>tryCreate</code> function; i.e. a function that returns <code>Some CprNumber</code> if the input is valid, or <code>None</code> if it isn't. In <a href="https://www.haskell.org">Haskell</a>, this pattern is called a <em>smart constructor</em>. </p> <p> There's a couple of rules to check. All integer values must fall in certain ranges. Days must be between 1 and 31, months must be between 1 and 12, and so on. One way to enable succinct checks like that is with an <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/active-patterns">active pattern</a>: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;<span style="color:blue;">private</span>&nbsp;(|<span style="color:navy;">Between</span>|_|)&nbsp;min&nbsp;max&nbsp;candidate&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;min&nbsp;&lt;=&nbsp;candidate&nbsp;&amp;&amp;&nbsp;candidate&nbsp;&lt;=&nbsp;max &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">then</span>&nbsp;<span style="color:navy;">Some</span>&nbsp;candidate &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">else</span>&nbsp;<span style="color:navy;">None</span></pre> </p> <p> Straightforward: return <code>Some candidate</code> if <code>candidate</code> is between <code>min</code> and <code>max</code>; otherwise, <code>None</code>. This enables you to pattern-match input integer values to particular ranges. </p> <p> Perhaps you've already noticed that years are represented with only two digits. CPR is an old system (from 1968), and back then, bits were expensive. No reason to waste bits on recording the millennium or century in which people were born. It turns out, after all, that there's a way to at least partially figure out the century in which people were born. The first digit of the sequence number contains that information: </p> <p> <pre><span style="color:green;">//&nbsp;int&nbsp;-&gt;&nbsp;int&nbsp;-&gt;&nbsp;int</span> <span style="color:blue;">let</span>&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:navy;">calculateFourDigitYear</span>&nbsp;year&nbsp;sequenceNumber&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;centuryDigit&nbsp;=&nbsp;sequenceNumber&nbsp;/&nbsp;1000&nbsp;<span style="color:green;">//&nbsp;Integer&nbsp;division</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;Table&nbsp;from&nbsp;https://da.wikipedia.org/wiki/CPR-nummer</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;centuryDigit,&nbsp;year&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:navy;">Between</span>&nbsp;0&nbsp;3&nbsp;_,&nbsp;_&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;1900 &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;4&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;,&nbsp;<span style="color:navy;">Between</span>&nbsp;0&nbsp;36&nbsp;_&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;2000 &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;4&nbsp;&nbsp;&nbsp;&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;">-&gt;</span>&nbsp;1900 &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:navy;">Between</span>&nbsp;5&nbsp;8&nbsp;_,&nbsp;<span style="color:navy;">Between</span>&nbsp;0&nbsp;57&nbsp;_&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;2000 &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:navy;">Between</span>&nbsp;5&nbsp;8&nbsp;_,&nbsp;_&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;1800 &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;_&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;,&nbsp;<span style="color:navy;">Between</span>&nbsp;0&nbsp;36&nbsp;_&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;2000 &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;_&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&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;">-&gt;</span>&nbsp;1900 &nbsp;&nbsp;&nbsp;&nbsp;+&nbsp;year</pre> </p> <p> As the code comment informs the reader, there's a table that defines the century, based on the two-digit year and the first digit of the sequence number. Note that birth dates in the nineteenth century are possible. No Danes born before 1900 are alive any longer, but at the time the CPR system was introduced, one person in the system was born in 1863! </p> <p> The <code>calculateFourDigitYear</code> function starts by pulling the first digit out of the sequence number. This is a four-digit number, so dividing by 1,000 produces the digit. I left a comment about integer division, because I often miss that detail when I read code. </p> <p> The big pattern-match expression uses the <code>Between</code> active pattern, but it ignores the return value from the pattern. This explains the wild cards (<code>_</code>), I hope. </p> <p> Although a pattern-match expression is often formatted over several lines of code, it's a single expression that produces a single value. Often, you see code where a <code>let</code>-binding binds a named value to a pattern-match expression. Another occasional idiom is to pipe a pattern-match expression to a function. In the <code>calculateFourDigitYear</code> function I use a language construct I've never seen anywhere else: the eight-lines pattern-match expression returns an <code>int</code>, which I simply add to <code>year</code> using the <code>+</code> operator. </p> <p> Both <code>calculateFourDigitYear</code> and the <code>Between</code> active pattern are private functions. They're only there as support functions for the public API. You can now implement a <code>tryCreate</code> function: </p> <p> <pre><span style="color:green;">//&nbsp;int&nbsp;-&gt;&nbsp;int&nbsp;-&gt;&nbsp;int&nbsp;-&gt;&nbsp;int&nbsp;-&gt;&nbsp;CprNumber&nbsp;option</span> <span style="color:blue;">let</span>&nbsp;<span style="color:navy;">tryCreate</span>&nbsp;day&nbsp;month&nbsp;year&nbsp;sequenceNumber&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;month,&nbsp;year,&nbsp;sequenceNumber&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:navy;">Between</span>&nbsp;1&nbsp;12&nbsp;m,&nbsp;<span style="color:navy;">Between</span>&nbsp;0&nbsp;99&nbsp;y,&nbsp;<span style="color:navy;">Between</span>&nbsp;0&nbsp;9999&nbsp;s&nbsp;<span style="color:blue;">-&gt;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;fourDigitYear&nbsp;=&nbsp;<span style="color:navy;">calculateFourDigitYear</span>&nbsp;y&nbsp;s &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;1&nbsp;&lt;=&nbsp;day&nbsp;&amp;&amp;&nbsp;day&nbsp;&lt;=&nbsp;<span style="color:teal;">DateTime</span>.<span style="color:navy;">DaysInMonth</span>&nbsp;(fourDigitYear,&nbsp;m) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">then</span>&nbsp;<span style="color:navy;">Some</span>&nbsp;(<span style="color:navy;">CprNumber</span>&nbsp;(day,&nbsp;m,&nbsp;y,&nbsp;s)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">else</span>&nbsp;<span style="color:navy;">None</span> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;_&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:navy;">None</span></pre> </p> <p> The <code>tryCreate</code> function begins by pattern-matching a triple (3-tuple) using the <code>Between</code> active pattern. The <code>month</code> must always be between <code>1</code> and <code>12</code> (both included), the <code>year</code> must be between <code>0</code> and <code>99</code>, and the <code>sequenceNumber</code> must always be between <code>0</code> and <code>9999</code> (in fact, I'm not completely sure if <code>0000</code> is valid). </p> <p> Finding the appropriate range for the <code>day</code> is more intricate. Is <code>31</code> always valid? Clearly not, because there's no November 31, for example. Is <code>30</code> always valid? No, because there's never a February 30. Is <code>29</code> valid? This depends on whether or not the year is a leap year. </p> <p> This reveals why you need <code>calculateFourDigitYear</code>. While you can use <code>DateTime.DaysInMonth</code> to figure out how many days a given month has, you need the year. Specifically, February 19<strong>00</strong> had 28 days, while February 20<strong>00</strong> had 29. </p> <p> Ergo, if <code>day</code>, <code>month</code>, <code>year</code>, and <code>sequenceNumber</code> all fall within their appropriate ranges, <code>tryCreate</code> returns a <code>Some CprNumber</code> value; otherwise, it returns <code>None</code>. </p> <p> Notice how this is different from an object-oriented constructor with guard clauses. If you try to create an object with invalid input, it'll throw an exception. If you try to create a <code>CprNumber</code> value, you'll receive a <code>CprNumber option</code>, and you, as the client developer, <em>must</em> handle both the <code>Some</code> and the <code>None</code> case. The compiler will enforce this. </p> <p> <pre>&gt; let gjern = Cpr.tryCreate 11 11 11 1118;; val gjern : Cpr.CprNumber option = Some 111111-1118 &gt; gjern |&gt; Option.map Cpr.born;; val it : DateTime option = Some 11.11.1911 00:00:00</pre> </p> <p> As most F# developers know, F# gives you enough syntactic sugar to make this a joy rather than a chore... and the warm and fuzzy feeling of safety is priceless. </p> <h3 id="78793bd7fceb4dc99bab81ccb7abb305"> CPR data <a href="#78793bd7fceb4dc99bab81ccb7abb305" title="permalink">#</a> </h3> <p> The above FSI session uses <code>Cpr.born</code>, which you haven't seen yet. With the tools available so far, it's trivial to implement; all the work is already done: </p> <p> <pre><span style="color:green;">//&nbsp;CprNumber&nbsp;-&gt;&nbsp;DateTime</span> <span style="color:blue;">let</span>&nbsp;<span style="color:navy;">born</span>&nbsp;(<span style="color:navy;">CprNumber</span>&nbsp;(day,&nbsp;month,&nbsp;year,&nbsp;sequenceNumber))&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:teal;">DateTime</span>&nbsp;(<span style="color:navy;">calculateFourDigitYear</span>&nbsp;year&nbsp;sequenceNumber,&nbsp;month,&nbsp;day)</pre> </p> <p> While the <code>CprNumber</code> case constructor is <code>private</code>, it's still available from inside of the module. The <code>born</code> function pattern-matches <code>day</code>, <code>month</code>, <code>year</code>, and <code>sequenceNumber</code> out of its input argument, and trivially delegates the hard work to <code>calculateFourDigitYear</code>. </p> <p> Another piece of data you can deduce from a CPR number is the gender of the person: </p> <p> <pre><span style="color:green;">//&nbsp;CprNumber&nbsp;-&gt;&nbsp;bool</span> <span style="color:blue;">let</span>&nbsp;<span style="color:navy;">isFemale</span>&nbsp;(<span style="color:navy;">CprNumber</span>&nbsp;(_,&nbsp;_,&nbsp;_,&nbsp;sequenceNumber))&nbsp;=&nbsp;sequenceNumber&nbsp;%&nbsp;2&nbsp;&nbsp;=&nbsp;0 <span style="color:blue;">let</span>&nbsp;<span style="color:navy;">isMale</span>&nbsp;&nbsp;&nbsp;(<span style="color:navy;">CprNumber</span>&nbsp;(_,&nbsp;_,&nbsp;_,&nbsp;sequenceNumber))&nbsp;=&nbsp;sequenceNumber&nbsp;%&nbsp;2&nbsp;&lt;&gt;&nbsp;0</pre> </p> <p> The rule is that if the sequence number is even, then the person is female; otherwise, the person is male (and if you change sex, you get a new CPR number). </p> <p> <pre>&gt; gjern |&gt; Option.map Cpr.isFemale;; val it : bool option = Some true</pre> </p> <p> Since <code>1118</code> is even, this is a woman. </p> <h3 id="235df75fd03a41e49b5a1fc3767e6ce8"> Parsing CPR strings <a href="#235df75fd03a41e49b5a1fc3767e6ce8" title="permalink">#</a> </h3> <p> CPR numbers are often passed around as text, so you'll need to be able to parse a <code>string</code> representation. As described in the <a href="http://blog.ploeh.dk/2018/11/26/the-test-data-generator-applicative-functor">previous article</a>, you should follow <a href="https://en.wikipedia.org/wiki/Robustness_principle">Postel's law</a>. Input could include extra white space, and the middle dash could be missing. </p> <p> The .NET Base Class Library contains enough utility methods working on <code>string</code> values that this isn't going to be particularly difficult. It can, however, be awkward to interoperate with object-oriented APIs, so you'll often benefit from adding a few utility functions that give you curried functions instead of objects with methods. Here's one that adapts <code>Int32.TryParse</code>: </p> <p> <pre><span style="color:blue;">module</span>&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:teal;">Int</span>&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;string&nbsp;-&gt;&nbsp;int&nbsp;option</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;<span style="color:navy;">tryParse</span>&nbsp;candidate&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;candidate&nbsp;|&gt;&nbsp;<span style="color:teal;">Int32</span>.<span style="color:navy;">TryParse</span>&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:blue;">true</span>,&nbsp;i&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:navy;">Some</span>&nbsp;i &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> Nothing much goes on here. While F# has pleasant syntax for handling <code>out</code> parameters, it can be inconvenient to have to pattern-match every time you'd like to try to parse an integer. </p> <p> Here's another helper function: </p> <p> <pre><span style="color:blue;">module</span>&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:teal;">String</span>&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;int&nbsp;-&gt;&nbsp;int&nbsp;-&gt;&nbsp;string&nbsp;-&gt;&nbsp;string&nbsp;option</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;<span style="color:navy;">trySubstring</span>&nbsp;startIndex&nbsp;length&nbsp;(s&nbsp;:&nbsp;<span style="color:teal;">string</span>)&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;s.Length&nbsp;&lt;&nbsp;startIndex&nbsp;+&nbsp;length &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">then</span>&nbsp;<span style="color:navy;">None</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">else</span>&nbsp;<span style="color:navy;">Some</span>&nbsp;(s.<span style="color:navy;">Substring</span>&nbsp;(startIndex,&nbsp;length))</pre> </p> <p> This one comes with two benefits: The first benefit is that it's curried, which enables partial application and piping. You'll see an example of this further down. The second benefit is that it handles at least one error condition in a type-safe manner. When trying to extract a sub-string from a string, the <code>Substring</code> <em>method</em> can throw an exception if the index or length arguments are out of range. This function checks whether it can extract the requested sub-string, and returns <code>None</code> if it can't. </p> <p> I wouldn't be surprised if there are edge cases (for example involving negative integers) that <code>trySubstring</code> doesn't handle gracefully, but as you may have noticed, this is a function in a <code>private</code> module. I only need it to handle a particular use case, and it does that. </p> <p> You can now add the <code>tryParse</code> function: </p> <p> <pre><span style="color:green;">//&nbsp;string&nbsp;-&gt;&nbsp;CprNumber&nbsp;option</span> <span style="color:blue;">let</span>&nbsp;<span style="color:navy;">tryParse</span>&nbsp;(candidate&nbsp;:&nbsp;<span style="color:teal;">string</span>&nbsp;)&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;(&lt;*&gt;)&nbsp;fo&nbsp;xo&nbsp;=&nbsp;fo&nbsp;|&gt;&nbsp;<span style="color:teal;">Option</span>.<span style="color:navy;">bind</span>&nbsp;(<span style="color:blue;">fun</span>&nbsp;<span style="color:navy;">f</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;xo&nbsp;|&gt;&nbsp;<span style="color:teal;">Option</span>.<span style="color:navy;">map</span>&nbsp;<span style="color:navy;">f</span>) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;canonicalized&nbsp;=&nbsp;candidate.<span style="color:navy;">Trim</span>().<span style="color:navy;">Replace</span>(<span style="color:#a31515;">&quot;-&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;&quot;</span>) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;dayCandidate&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;canonicalized&nbsp;|&gt;&nbsp;<span style="color:teal;">String</span>.<span style="color:navy;">trySubstring</span>&nbsp;0&nbsp;2 &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;monthCandidate&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;canonicalized&nbsp;|&gt;&nbsp;<span style="color:teal;">String</span>.<span style="color:navy;">trySubstring</span>&nbsp;2&nbsp;2 &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;yearCandidate&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;canonicalized&nbsp;|&gt;&nbsp;<span style="color:teal;">String</span>.<span style="color:navy;">trySubstring</span>&nbsp;4&nbsp;2 &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;sequenceNumberCandidate&nbsp;=&nbsp;canonicalized&nbsp;|&gt;&nbsp;<span style="color:teal;">String</span>.<span style="color:navy;">trySubstring</span>&nbsp;6&nbsp;4 &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:navy;">Some</span>&nbsp;<span style="color:navy;">tryCreate</span> &nbsp;&nbsp;&nbsp;&nbsp;&lt;*&gt;&nbsp;<span style="color:teal;">Option</span>.<span style="color:navy;">bind</span>&nbsp;<span style="color:teal;">Int</span>.<span style="color:navy;">tryParse</span>&nbsp;dayCandidate &nbsp;&nbsp;&nbsp;&nbsp;&lt;*&gt;&nbsp;<span style="color:teal;">Option</span>.<span style="color:navy;">bind</span>&nbsp;<span style="color:teal;">Int</span>.<span style="color:navy;">tryParse</span>&nbsp;monthCandidate &nbsp;&nbsp;&nbsp;&nbsp;&lt;*&gt;&nbsp;<span style="color:teal;">Option</span>.<span style="color:navy;">bind</span>&nbsp;<span style="color:teal;">Int</span>.<span style="color:navy;">tryParse</span>&nbsp;yearCandidate &nbsp;&nbsp;&nbsp;&nbsp;&lt;*&gt;&nbsp;<span style="color:teal;">Option</span>.<span style="color:navy;">bind</span>&nbsp;<span style="color:teal;">Int</span>.<span style="color:navy;">tryParse</span>&nbsp;sequenceNumberCandidate &nbsp;&nbsp;&nbsp;&nbsp;|&gt;&nbsp;&nbsp;<span style="color:teal;">Option</span>.<span style="color:navy;">bind</span>&nbsp;<span style="color:navy;">id</span></pre> </p> <p> The function starts by defining a private <code>&lt;*&gt;</code> operator. Readers of the <a href="http://blog.ploeh.dk/2018/10/01/applicative-functors">applicative functor article series</a> will recognise this as the 'apply' operator. The reason I added it as a private operator is that I don't need it anywhere else in the code base, and in F#, I'm always worried that if I add <code>&lt;*&gt;</code> at a more visible level, it could collide with other definitions of <code>&lt;*&gt;</code> - for example <a href="http://blog.ploeh.dk/2018/10/08/full-deck">one for lists</a>. This one particularly makes <code>option</code> an applicative functor. </p> <p> The first step in parsing <code>candidate</code> is to remove surrounding white space and the interior dash. </p> <p> The next step is to use <code>String.trySubstring</code> to pull out candidates for <em>day</em>, <em>month</em>, and so on. Each of these four are <code>string option</code> values. </p> <p> All four of these must be <code>Some</code> values before we can even start to attempt to turn them into a <code>CprNumber</code> value. If only a single value is <code>None</code>, <code>tryParse</code> should return <code>None</code> as well. </p> <p> You may want to re-read the <a href="http://blog.ploeh.dk/2018/10/15/an-applicative-password-list">article on the List applicative functor</a> for a detailed explanation of how the <code>&lt;*&gt;</code> operator works. In <code>tryParse</code>, you have four <code>option</code> values, so you apply them all using four <code>&lt;*&gt;</code> operators. Since four values are being applied, you'll need a function that takes four curried input arguments of the appropriate types. In this case, all four are <code>int option</code> values, so for the first expression in the <code>&lt;*&gt;</code> chain, you'll need an option of a function that takes four <code>int</code> arguments. </p> <p> Lo and behold! <code>tryCreate</code> takes four <code>int</code> arguments, so the only action you need to take is to make it an <code>option</code> by putting it in a <code>Some</code> case. </p> <p> The only remaining hurdle is that <code>tryCreate</code> returns <code>CprNumber option</code>, and since you're already 'in' the <code>option</code> applicative functor, you now have a <code>CprNumber option option</code>. Fortunately, <code>bind id</code> is always the 'flattening' combo, so that's easily dealt with. </p> <p> <pre>&gt; let andreas = Cpr.tryParse " 0109636221";; val andreas : Cpr.CprNumber option = Some 010963-6221</pre> </p> <p> Since you now have both a way to parse a string, and turn a <code>CprNumber</code> into a string, you can write the usual round-trip property: </p> <p> <pre>[&lt;<span style="color:teal;">Fact</span>&gt;] <span style="color:blue;">let</span>&nbsp;<span style="color:navy;">``CprNumber&nbsp;correctly&nbsp;round-trips``</span>&nbsp;()&nbsp;=&nbsp;<span style="color:teal;">Property</span>.<span style="color:navy;">check</span>&nbsp;&lt;|&nbsp;<span style="color:blue;">property</span>&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;expected&nbsp;=&nbsp;<span style="color:teal;">Gen</span>.cprNumber &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;&nbsp;actual&nbsp;&nbsp;&nbsp;=&nbsp;expected&nbsp;|&gt;&nbsp;<span style="color:navy;">string</span>&nbsp;|&gt;&nbsp;<span style="color:teal;">Cpr</span>.<span style="color:navy;">tryParse</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:navy;">Some</span>&nbsp;expected&nbsp;=!&nbsp;actual&nbsp;}</pre> </p> <p> This test uses <a href="https://github.com/hedgehogqa/fsharp-hedgehog">Hedgehog</a>, <a href="https://github.com/SwensenSoftware/unquote">Unquote</a>, and <a href="https://xunit.github.io">xUnit.net</a>. The previous article demonstrates a way to test that <code>Cpr.tryParse</code> can handle mangled input. </p> <h3 id="503bb1791d344b1f917734cffe2320f6"> Summary <a href="#503bb1791d344b1f917734cffe2320f6" title="permalink">#</a> </h3> <p> This article mostly exhibited various F# design techniques you can use to achieve an even better degree of encapsulation than you can easily get with object-oriented languages. Towards the end, you saw how using <code>option</code> as an applicative functor enables you to compose more complex optional values from smaller values. If just a single value is <code>None</code>, the entire expression becomes <code>None</code>, but if all values are <code>Some</code> values, the computation succeeds. </p> <p> This article is an entry in the <a href="https://sergeytihon.com/2018/10/22/f-advent-calendar-in-english-2018">F# Advent Calendar in English 2018</a>. </p> <p> <strong>Next: </strong> <a href="http://blog.ploeh.dk/2018/12/17/the-lazy-applicative-functor">The Lazy applicative functor</a>. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="559c8543d61042a0bdcbe938ac97de12"> <div class="comment-author"><a href="https://activesolution.se">Viktor Andersson</a></div> <div class="comment-content"> <p> Great post, a very good read! Interestingly enough we recently made an F# implementation for the swedish personal identification number. In fact <a href="https://github.com/ActiveLogin/ActiveLogin.Identity">v1.0.0</a> will be published any day now. Interesting to see how the problem with four-digit years are handled differently in Denmark and Sweden. </p> <p> I really like the Between Active pattern of your solution, we did not really take as a generic approach, instead we modeled with types for Year, Month, Day, etc. But I find your solution to be very concise and clear. Also we worked with the Result type instead of Option to be able to provide the client with helpful error messages. For our Object Oriented friends we are also exposing a C#-friendly facade which adds a bit of boiler plate code. </p> </div> <div class="comment-date">2018-12-18 06:26 UTC</div> </div> <div class="comment" id="26683afcb79c444f9887f112323b935a"> <div class="comment-author"><a href="http://blog.ploeh.dk">Mark Seemann</a></div> <div class="comment-content"> <p> Viktor, thank you for your kind words. The <code>Result</code> (or <a href="http://blog.ploeh.dk/2018/06/11/church-encoded-either">Either</a>) type does, indeed, provide more information when things go wrong. This can be useful when client code needs to handle different error cases in different ways. Sometimes, it may also be useful, as you write, when you want to provide more <a href="http://blog.ploeh.dk/2014/12/23/exception-messages-are-for-programmers">helpful error messages</a>. </p> <p> Particularly when it comes to parsing or input validation, <a href="http://blog.ploeh.dk/2018/11/05/applicative-validation">Either can be useful</a>. </p> <p> The main reason I chose to model with <code>option</code> in this article was that I wanted to demonstrate how to use the <a href="http://blog.ploeh.dk/2018/10/01/applicative-functors">applicative</a> nature of <code>option</code>, but I suppose I could have equally done so with <code>Result</code>. </p> </div> <div class="comment-date">2018-12-18 9:09 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please consider <a href="http://blog.ploeh.dk/support">supporting it</a>. Set is not a functor http://blog.ploeh.dk/2018/12/03/set-is-not-a-functor 2018-12-03T07:58:00+00:00 Mark Seemann <div id="post"> <p> <em>Sets aren't functors. An 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>. The way functors are frequently presented to programmes is as a generic <a href="https://bartoszmilewski.com/2014/01/14/functors-are-containers">container</a> (<code>Foo&lt;T&gt;</code>) equipped with a translation method, normally called <em>map</em>, but in C# <a href="http://blog.ploeh.dk/2015/08/03/idiomatic-or-idiosyncratic">idiomatically</a> called <code>Select</code>. </p> <p> It'd be tempting to believe that any generic type with a <code>Select</code> method is a functor, but it takes more than that. The <code>Select</code> method must also obey the <a href="http://blog.ploeh.dk/2018/03/22/functors">functor laws</a>. This article shows an example of a translation that violates the second functor law. </p> <h3 id="5a13402d14f54ce689a7ae4e62f54233"> Mapping sets <a href="#5a13402d14f54ce689a7ae4e62f54233" title="permalink">#</a> </h3> <p> The .NET Base Class Library comes with a class called <a href="https://docs.microsoft.com/en-gb/dotnet/api/system.collections.generic.hashset-1">HashSet&lt;T&gt;</a>. This generic class implements <code>IEnumerable&lt;T&gt;</code>, so, via extension methods, it has a <code>Select</code> method. </p> <p> Unfortunately, that <code>Select</code> method isn't a structure-preserving translation of sets. The problem is that it treats sets as enumerable sequences, which implies an order to elements that isn't part of a set's structure. </p> <p> In order to understand what the problem is, consider this <a href="https://xunit.github.io">xUnit.net</a> test: </p> <p> <pre>[<span style="color:#2b91af;">Fact</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SetAsEnumerableSelectLeadsToWrongConclusions() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;set1&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">HashSet</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;{&nbsp;1,&nbsp;2,&nbsp;3&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;set2&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">HashSet</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;{&nbsp;3,&nbsp;2,&nbsp;1&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.True(set1.SetEquals(set2)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">int</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;id&nbsp;=&nbsp;x&nbsp;=&gt;&nbsp;x; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;seq1&nbsp;=&nbsp;set1.AsEnumerable().Select(id); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;seq2&nbsp;=&nbsp;set2.AsEnumerable().Select(id); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.False(seq1.SequenceEqual(seq2)); }</pre> </p> <p> This test creates two sets, and by using a <a href="http://xunitpatterns.com/Guard%20Assertion.html">Guard Assertion</a> demonstrates that they're equal to each other. It then proceeds to <code>Select</code> over both sets, using the identity function <code>id</code>. The return values aren't <code>HashSet&lt;T&gt;</code> objects, but rather <code>IEnumerable&lt;T&gt;</code> sequences. Due to an implementation detail in <code>HashSet&lt;T&gt;</code>, these two sequences are different, because they were populated in reverse order of each other. </p> <p> The problem is that the <code>Select</code> extension method has the signature <code>IEnumerable&lt;TResult&gt; Select&lt;T, TResult&gt;(IEnumerable&lt;T&gt;, Func&lt;T, TResult&gt;)</code>. It doesn't operate on <code>HashSet&lt;T&gt;</code>, but instead treats it as an ordered sequence of elements. A set isn't intrinsically ordered, so that's not the translation you need. </p> <p> To be clear, <code>IEnumerable&lt;T&gt;</code> <em>is</em> a functor (as long as the sequence is <a href="https://en.wikipedia.org/wiki/Referential_transparency">referentially transparent</a>). It's just not the functor you're looking for. What you need is a method with the signature <code>HashSet&lt;TResult&gt; Select&lt;T, TResult&gt;(HashSet&lt;T&gt;, Func&lt;T, TResult&gt;)</code>. Fortunately, such a method is trivial to implement: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">HashSet</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;">HashSet</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;">HashSet</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;(source.AsEnumerable().Select(selector)); }</pre> </p> <p> This extension method offers a proper <code>Select</code> method that translates one <code>HashSet&lt;T&gt;</code> into another. It does so by enumerating the elements of the set, then using the <code>Select</code> method for <code>IEnumerable&lt;T&gt;</code>, and finally wrapping the resulting sequence in a new <code>HashSet&lt;TResult&gt;</code> object. </p> <p> This is a better candidate for a translation of sets. Is it a functor, then? </p> <h3 id="44c78cf51897490a8d844a89eaa8ef73"> Second functor law <a href="#44c78cf51897490a8d844a89eaa8ef73" title="permalink">#</a> </h3> <p> Even though <code>HashSet&lt;T&gt;</code> and the new <code>Select</code> method have the correct types, it's still only a functor if it obeys the functor laws. It's easy, however, to come up with a counter-example that demonstrates that <code>Select</code> violates the second functor law. </p> <p> Consider a pair of conversion methods between <code>string</code> and <code>DateTimeOffset</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;ParseDateTime(<span style="color:blue;">string</span>&nbsp;s) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;dt; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(<span style="color:#2b91af;">DateTimeOffset</span>.TryParse(s,&nbsp;<span style="color:blue;">out</span>&nbsp;dt)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;dt; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>.MinValue; } <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">string</span>&nbsp;FormatDateTime(<span style="color:#2b91af;">DateTimeOffset</span>&nbsp;dt) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;dt.ToString(<span style="color:#a31515;">&quot;yyyy&#39;-&#39;MM&#39;-&#39;dd&#39;T&#39;HH&#39;:&#39;mm&#39;:&#39;sszzz&quot;</span>); }</pre> </p> <p> The first method, <code>ParseDateTime</code>, converts a <code>string</code> into a <code>DateTimeOffset</code> value. It tries to parse the input, and returns the corresponding <code>DateTimeOffset</code> value if this is possible; for all other input values, it simply returns <code>DateTimeOffset.MinValue</code>. You may dislike how the method deals with input values it can't parse, but that's not important. In order to prove that sets aren't functors, I just need <em>one</em> counter-example, and the one I'll pick will not involve unparseable strings. </p> <p> The <code>FormatDateTime</code> method converts any <code>DateTimeOffset</code> value to an <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601 string</a>. </p> <p> The <code>DateTimeOffset</code> type is the interesting piece of the puzzle. In case you're not intimately familiar with it, a <code>DateTimeOffset</code> value contains a date, a time, and a time-zone offset. You can, for example create one like this: </p> <p> <pre>&gt; <span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>(2018,&nbsp;4,&nbsp;17,&nbsp;15,&nbsp;9,&nbsp;55,&nbsp;<span style="color:#2b91af;">TimeSpan</span>.FromHours(2)) [17.04.2018 15:09:55 +02:00]</pre> </p> <p> This represents April 17, 2018, at 15:09:55 at UTC+2. You can convert that value to UTC: </p> <p> <pre>&gt; <span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">DateTimeOffset</span>(2018,&nbsp;4,&nbsp;17,&nbsp;15,&nbsp;9,&nbsp;55,&nbsp;<span style="color:#2b91af;">TimeSpan</span>.FromHours(2)).ToUniversalTime() [17.04.2018 13:09:55 +00:00]</pre> </p> <p> This value clearly contains different constituent elements, but it does represent the same instant in time. This is how <code>DateTimeOffset</code> implements <code>Equals</code>. These two object are considered equal, as the following test will demonstrate. </p> <p> In a sense, you could argue that there's some sense in implementing equality for <code>DateTimeOffset</code> in that way, but this unusual behaviour provides just the counter-example that demonstrates that sets aren't functors: </p> <p> <pre>[<span style="color:#2b91af;">Fact</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;SetViolatesSecondFunctorLaw() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;x&nbsp;=&nbsp;<span style="color:#a31515;">&quot;2018-04-17T13:05:28+02:00&quot;</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;y&nbsp;=&nbsp;<span style="color:#a31515;">&quot;2018-04-17T11:05:28+00:00&quot;</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.Equal(ParseDateTime(x),&nbsp;ParseDateTime(y)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;set&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">HashSet</span>&lt;<span style="color:blue;">string</span>&gt;&nbsp;{&nbsp;x,&nbsp;y&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;l&nbsp;=&nbsp;set.Select(ParseDateTime).Select(FormatDateTime); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;r&nbsp;=&nbsp;set.Select(s&nbsp;=&gt;&nbsp;FormatDateTime(ParseDateTime(s))); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.False(l.SetEquals(r)); }</pre> </p> <p> This passing test provides the required counter-example. It first creates two ISO 8601 representations of the same instant. As the Guard Assertion demonstrates, the corresponding <code>DateTimeOffset</code> values are considered equal. </p> <p> In <a href="http://blog.ploeh.dk/2013/06/24/a-heuristic-for-formatting-code-according-to-the-aaa-pattern">the <em>act</em> phase</a>, the test creates a <code>set</code> of these two strings. It then performs two round-trips over <code>DateTimeOffset</code> and back to <code>string</code>. The second functor law states that it shouldn't matter whether you do it in one or two steps, but it does. <code>Assert.False</code> passes because <code>l</code> is <em>not</em> equal to <code>r</code>. Q.E.D. </p> <h3 id="f392310c11984d08a31bf6456849dd01"> An illustration <a href="#f392310c11984d08a31bf6456849dd01" title="permalink">#</a> </h3> <p> The problem is that sets only contain one element of each value, and due to the way that <code>DateTimeOffset</code> interprets equality, two values that both represent the same instant are collapsed into a single element when taking an intermediary step. You can illustrate it like this: </p> <p> <img src="/content/binary/set-violating-second-functor-law.png" alt="Diagram illustrating the above counter-example."> </p> <p> In this illustration, I've hidden the date behind an ellipsis in order to improve clarity. The date segments are irrelevant in this example, since they're all identical. </p> <p> You start with a set of two <code>string</code> values. These are obviously different, so the set contains two elements. When you map the set using the <code>ParseDateTime</code> function, you get two <code>DateTimeOffset</code> values that .NET considers equal. For that reason, <code>HashSet&lt;DateTimeOffset&gt;</code> considers the second value redundant, and ignores it. Therefore, the intermediary set contains only a single element. When you map that set with <code>FormatDateTime</code>, there's only a single element to translate, so the final set contains only a single <code>string</code> value. </p> <p> On the other hand, when you map the input set without an intermediary set, each <code>string</code> value is first converted into a <code>DateTimeOffset</code> value, and then immediately thereafter converted back to a <code>string</code> value. Since the two resulting strings are different, the resulting set contains two values. </p> <p> Which of these paths is correct, then? Both of them. That's the problem. When considering the semantics of sets, both translations produce correct results. Since the results diverge, however, the translation isn't a functor. </p> <h3 id="ee52a36b611b40c5a7d015bea3cbf1dc"> Summary <a href="#ee52a36b611b40c5a7d015bea3cbf1dc" title="permalink">#</a> </h3> <p> A functor must not only preserve the structure of the data container, but also of functions. The functor laws express that a translation of functions preserves the structure of how the functions compose, in addition to preserving the structure of the containers. Mapping a set doesn't preserve those structures, and that's the reason that sets aren't functors. </p> <h3 id="649aceb6a241450abc861ec63f34ff0a"> P.S. <a href="#649aceb6a241450abc861ec63f34ff0a" title="permalink">#</a> </h3> <p> <strong>2019-01-09.</strong> There's been some controversy around this post, and more than one person has pointed out to me that the underlying reason that the functor laws are violated in the above example is because <code>DateTimeOffset</code> behaves oddly. Specifically, its <code>Equals</code> implementation breaks the <em>substitution property</em> of equality. See e.g. <a href="https://giacomociti.github.io">Giacomo Citi</a>'s <a href="https://giacomociti.github.io/2019/01/02/Abstract-types-are-more-equal.html">response</a> for details. </p> <p> The term <em>functor</em> originates from <a href="https://en.wikipedia.org/wiki/Category_theory">category theory</a>, and I don't claim to be an expert on that topic. It's unclear to me if the underlying concept of <em>equality</em> is explicitly defined in category theory, but it wouldn't surprise me if it is. If that definition involves the substitution property, then the counter-example presented here says nothing about Set as a functor, but rather that <code>DateTimeOffset</code> has unlawful equality behaviour. </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 consider <a href="http://blog.ploeh.dk/support">supporting it</a>. The Test Data Generator applicative functor http://blog.ploeh.dk/2018/11/26/the-test-data-generator-applicative-functor 2018-11-26T07:24:00+00:00 Mark Seemann <div id="post"> <p> <em>Test Data Generator modelled as an applicative functor, with examples in C# and 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>. It shows yet another example of an applicative functor. I tend to think of applicative functors as an abstraction of 'combinations' of values and functions, but this is most evident for lists and other collections. Even so, I think that the intuition also holds for <a href="http://blog.ploeh.dk/2018/10/29/the-maybe-applicative-functor">Maybe as an applicative functor</a> as well as <a href="http://blog.ploeh.dk/2018/11/05/applicative-validation">validation as an applicative functor</a>. This is also the case for the <a href="http://blog.ploeh.dk/2017/09/18/the-test-data-generator-functor">Test Data Generator functor</a>. </p> <h3 id="bc5212f7353f44f793ed20399d359bfe"> Applicative generator in C# <a href="#bc5212f7353f44f793ed20399d359bfe" title="permalink">#</a> </h3> <p> In a <a href="http://blog.ploeh.dk/2017/09/18/the-test-data-generator-functor">previous article</a>, you saw how to implement a Test Data Generator as a functor in C#. The core class is this <code>Generator&lt;T&gt;</code> class: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Generator</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;">Func</span>&lt;<span style="color:#2b91af;">Random</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;generate; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Generator(<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Random</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;&nbsp;generate) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(generate&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>(generate)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.generate&nbsp;=&nbsp;generate; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Generator</span>&lt;<span style="color:#2b91af;">T1</span>&gt;&nbsp;Select&lt;<span style="color:#2b91af;">T1</span>&gt;(<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">T1</span>&gt;&nbsp;f) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(f&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>(f)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Random</span>,&nbsp;<span style="color:#2b91af;">T1</span>&gt;&nbsp;newGenerator&nbsp;=&nbsp;r&nbsp;=&gt;&nbsp;f(<span style="color:blue;">this</span>.generate(r)); &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;">Generator</span>&lt;<span style="color:#2b91af;">T1</span>&gt;(newGenerator); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Generate(<span style="color:#2b91af;">Random</span>&nbsp;random) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(random&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>(random)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.generate(random); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> This is merely repetition from the earlier article. </p> <p> <code>Generator&lt;T&gt;</code> is already a functor, but you can make it an <em>applicative</em> functor by adding an extension method like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Generator</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;">Generator</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;">Generator</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;generator) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(selectors&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>(selectors)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(generator&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>(generator)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Random</span>,&nbsp;<span style="color:#2b91af;">TResult</span>&gt;&nbsp;newGenerator&nbsp;=&nbsp;r&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;f&nbsp;=&nbsp;selectors.Generate(r); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;x&nbsp;=&nbsp;generator.Generate(r); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;f(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;">Generator</span>&lt;<span style="color:#2b91af;">TResult</span>&gt;(newGenerator); }</pre> </p> <p> The <code>Apply</code> function combines a generator of functions with a generator of values. Given these two generators, it defines a closure over both, and packages that function in a new generator object. </p> <h3 id="58282543d8c4409cb596547e131bf249"> CPR example <a href="#58282543d8c4409cb596547e131bf249" title="permalink">#</a> </h3> <p> When is it interesting to combine a randomly selected function with a randomly generated value? Here's an example. </p> <p> In Denmark, everyone has a <a href="https://en.wikipedia.org/wiki/Personal_identification_number_(Denmark)">personal identification number</a>, in Danish called <em>CPR-nummer</em> (<em>CPR number</em>). It's somewhat comparable to the <a href="https://en.wikipedia.org/wiki/Social_Security_number">U.S. Social Security number</a>, but surely more Orwellian. </p> <p> CPR numbers have a simple format: <code>DDMMYY-SSSS</code>, where the first six digits indicate a person's birth date, and the last four digits are a sequence number. An example could be <code>010203-1234</code>, which indicates a woman born February 1, 1903. Assume that you're writing a system that has to accept CPR numbers as input. You've represented CPR number as a class called <code>CprNumber</code>, and you've already written a parser, but now it turns out that sometimes users enter slightly malformed data. </p> <p> Sometimes users copy and paste CPR numbers from other sources, and occasionally, they inadvertently include a leading or trailing space. Other users forget the dash between the birth date and the sequence number. In other words, sometimes you receive input like <code>"050301-4231 "</code> or <code>"1211993321"</code>. </p> <p> Using your fancy Test Data Generator, you'd like to write a test that verifies that your parser follows <a href="https://en.wikipedia.org/wiki/Robustness_principle">Postel's law</a>: <em>Be conservative in what you send, be liberal in what you accept</em>. </p> <p> Assume that you already have a generator that can produce valid <code>CprNumber</code> objects. One test strategy, then, could be to generate a valid <code>CprNumber</code> object, convert it to a string, slightly taint or mangle that string, and then attempt to parse the tainted string. </p> <p> There's more than one way to taint a valid CPR number string. You could, for example, define three functions like these: </p> <p> <pre><span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;addLeadingSpace&nbsp;=&nbsp;s&nbsp;=&gt;&nbsp;<span style="color:#a31515;">&quot;&nbsp;&quot;</span>&nbsp;+&nbsp;s; <span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;addTrailingSpace&nbsp;=&nbsp;s&nbsp;=&gt;&nbsp;s&nbsp;+&nbsp;<span style="color:#a31515;">&quot;&nbsp;&quot;</span>; <span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;removeDash&nbsp;=&nbsp;s&nbsp;=&gt;&nbsp;s.Replace(<span style="color:#a31515;">&quot;-&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;&quot;</span>);</pre> </p> <p> The first function adds a leading space to a string, the second adds a trailing space, and the third removes all dashes it finds. Can you make a generator out of those functions? </p> <p> Yes, you can, with this common general-purpose method: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Generator</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;Elements&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:blue;">params</span>&nbsp;<span style="color:#2b91af;">T</span>[]&nbsp;alternatives) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(alternatives&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>(alternatives)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Generator</span>&lt;<span style="color:#2b91af;">T</span>&gt;(r&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;index&nbsp;=&nbsp;r.Next(alternatives.Length); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;alternatives[index]; &nbsp;&nbsp;&nbsp;&nbsp;}); }</pre> </p> <p> This generator randomly selects a value from an array of values, with equal probability. It's a common method, because you'll find equivalent functions in <a href="https://en.wikipedia.org/wiki/QuickCheck">QuickCheck</a>, <a href="https://fscheck.github.io/FsCheck">FsCheck</a>, and <a href="https://github.com/hedgehogqa/fsharp-hedgehog">Hedgehog</a> (where it's called <code>item</code>). </p> <p> You can write the entire test like this: </p> <p> <pre>[<span style="color:#2b91af;">Fact</span>] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;ParseCorrectlyHandlesTaintedInput() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;addLeadingSpace&nbsp;=&nbsp;s&nbsp;=&gt;&nbsp;<span style="color:#a31515;">&quot;&nbsp;&quot;</span>&nbsp;+&nbsp;s; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;addTrailingSpace&nbsp;=&nbsp;s&nbsp;=&gt;&nbsp;s&nbsp;+&nbsp;<span style="color:#a31515;">&quot;&nbsp;&quot;</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;removeDash&nbsp;=&nbsp;s&nbsp;=&gt;&nbsp;s.Replace(<span style="color:#a31515;">&quot;-&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;&quot;</span>); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Generator</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;&gt;&nbsp;tainters&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Gen</span>.Elements( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;addLeadingSpace, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;addTrailingSpace, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;removeDash, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;s&nbsp;=&gt;&nbsp;addLeadingSpace(removeDash(s)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;s&nbsp;=&gt;&nbsp;addTrailingSpace(addLeadingSpace(s))); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;g&nbsp;=&nbsp;tainters.Apply(<span style="color:#2b91af;">Gen</span>.CprNumber.Select(n&nbsp;=&gt;&nbsp;n.ToString())); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;rnd&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Random</span>(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;candidate&nbsp;=&nbsp;g.Generate(rnd); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">CprNumber</span>&nbsp;dummy; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;actual&nbsp;=&nbsp;<span style="color:#2b91af;">CprNumber</span>.TryParse(candidate,&nbsp;<span style="color:blue;">out</span>&nbsp;dummy); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Assert</span>.True(actual); }</pre> </p> <p> You first define the three 'tainting' functions, and then create the <code>tainters</code> generator. Notice that this generator not only contains the three functions, but also combinations of these functions. I didn't include all possible combinations of functions, but in <a href="http://blog.ploeh.dk/2018/10/22/applicative-combinations-of-functions">an earlier article</a>, you saw how to do just that. </p> <p> <code>Gen.CprNumber</code> is a <code>Generator&lt;CprNumber&gt;</code>, while you actually need a <code>Generator&lt;string&gt;</code>. Since <code>Generator&lt;T&gt;</code> is a functor, you can easily map <code>Gen.CprNumber</code> with its <code>Select</code> method. </p> <p> You now have a <code>Generator&lt;Func&lt;string, string&gt;&gt;</code> (<code>tainters</code>) and a <code>Generator&lt;string&gt;</code>, so you can combine them using <code>Apply</code>. The result <code>g</code> is another <code>Generator&lt;string&gt;</code> that generates 'tainted', but still valid, CPR string representations. </p> <p> In order to keep the example as simple as possible, the <em>Arrange</em> and <em>Assert</em> phases of the test only checks if <code>CprNumber.TryParse</code> returns <code>true</code>. A better test would also verify that the resulting <code>CprNumber</code> value was correct, but in order to do that, you need to keep the originally generated <code>CprNumber</code> object around so that you can compare this expected value to the actual value. This is possible, but complicates the code, so I left it out of the example. </p> <h3 id="f3d0db787eaf4a018a593daaa78f9e17"> F# Hedgehog <a href="#f3d0db787eaf4a018a593daaa78f9e17" title="permalink">#</a> </h3> <p> You can translate the above unit test to F#, using <a href="https://github.com/hedgehogqa/fsharp-hedgehog">Hedgehog</a> as a property-based testing library. Another option would be <a href="https://fscheck.github.io/FsCheck">FsCheck</a>. Without further ado, I present to you the test: </p> <p> <pre>[&lt;<span style="color:teal;">Fact</span>&gt;] <span style="color:blue;">let</span>&nbsp;<span style="color:navy;">``Correctly&nbsp;parses&nbsp;tainted&nbsp;text``</span>&nbsp;()&nbsp;=&nbsp;<span style="color:teal;">Property</span>.<span style="color:navy;">check</span>&nbsp;&lt;|&nbsp;<span style="color:blue;">property</span>&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;<span style="color:navy;">removeDash</span>&nbsp;(s&nbsp;:&nbsp;<span style="color:teal;">string</span>)&nbsp;=&nbsp;s.<span style="color:navy;">Replace</span>&nbsp;(<span style="color:#a31515;">&quot;-&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;&quot;</span>) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;candidate&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:teal;">Gen</span>.<span style="color:navy;">item</span>&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:navy;">sprintf</span>&nbsp;<span style="color:#a31515;">&quot;&nbsp;</span><span style="color:teal;">%s</span><span style="color:#a31515;">&quot;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:navy;">sprintf</span>&nbsp;<span style="color:#a31515;">&quot;</span><span style="color:teal;">%s</span><span style="color:#a31515;">&nbsp;&quot;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:navy;">removeDash</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:navy;">removeDash</span>&nbsp;&gt;&gt;&nbsp;<span style="color:navy;">sprintf</span>&nbsp;<span style="color:#a31515;">&quot;&nbsp;</span><span style="color:teal;">%s</span><span style="color:#a31515;">&quot;</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:navy;">sprintf</span>&nbsp;<span style="color:#a31515;">&quot;&nbsp;</span><span style="color:teal;">%s</span><span style="color:#a31515;">&nbsp;&quot;</span>] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;*&gt;&nbsp;<span style="color:teal;">Gen</span>.<span style="color:navy;">map</span>&nbsp;<span style="color:navy;">string</span>&nbsp;<span style="color:teal;">Gen</span>.cprNumber &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;actual&nbsp;=&nbsp;<span style="color:teal;">Cpr</span>.<span style="color:navy;">tryParse</span>&nbsp;candidate &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:navy;">test</span>&nbsp;<span style="background:yellow;">&lt;@&nbsp;</span><span style="background:yellow;">actual</span><span style="background:yellow;">&nbsp;</span><span style="background:yellow;">|&gt;</span><span style="background:yellow;">&nbsp;</span><span style="color:teal;background:yellow;">Option</span><span style="background:yellow;">.</span><span style="color:navy;background:yellow;">isSome</span><span style="background:yellow;">&nbsp;@&gt;</span>&nbsp;}</pre> </p> <p> As I already mentioned in passing, Hedgehog's equivalent to the above <code>Elements</code> method is called <code>Gen.item</code>. Here, you see the same five functions as above passed in a list. Thanks to partial application and type inference, an expression like <code>sprintf " %s"</code> is already a function of the type <code>string -&gt; string</code>, as is <code>removeDash</code>. For the last of the five functions, I found it easier to write (and read) <code>sprintf " %s "</code> instead of <code>sprintf " %s" &gt;&gt; sprintf "%s "</code>. </p> <p> Equivalent to the C# example, <code>Gen.cprNumber</code> is a <code>Gen&lt;CprNumber&gt;</code>, so mapping it with the built-in <code>string</code> function translates it to a <code>Gen&lt;string&gt;</code>. </p> <p> Hedgehog already includes an <code>&lt;*&gt;</code> operator; <code>Gen</code> is an applicative functor. </p> <h3 id="f7c420f0d4e641a384749187d7bbf217"> Summary <a href="#f7c420f0d4e641a384749187d7bbf217" title="permalink">#</a> </h3> <p> Applicative functors are fairly common. I find it intuitive to think of them as an abstraction of how to make combinations of things. Modelling a Test Data Generator as an applicative functor enables you to create random combinations of functions and values. </p> <p> While working on the Hedgehog example, I discovered another great use of <code>option</code> as an applicative functor. You can see this in the next article. </p> <p> <strong>Next: </strong> <a href="http://blog.ploeh.dk/2018/12/10/danish-cpr-numbers-in-f">Danish CPR numbers in F#</a>. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="http://blog.ploeh.dk/support">supporting it</a>. Functional architecture: a definition http://blog.ploeh.dk/2018/11/19/functional-architecture-a-definition 2018-11-19T09:44:00+00:00 Mark Seemann <div id="post"> <p> <em>How do you know whether your software architecture follows good functional programming practices? Here's a way to tell.</em> </p> <p> Over the years, I've written articles on functional architecture, including <a href="http://blog.ploeh.dk/2016/03/18/functional-architecture-is-ports-and-adapters">Functional architecture is Ports and Adapters</a>, given <a href="https://vimeo.com/180287057">conference talks</a>, and even produced <a href="http://blog.ploeh.dk/functional-architecture-with-fsharp">a Pluralsight course</a> on the topic. How should we define <em>functional architecture</em>, though? </p> <p> People sometimes ask me about their <a href="https://fsharp.org">F#</a> code: <em>How do I know that my F# code is functional?</em> </p> <p> Please permit me a little detour before I answer that question. </p> <h3 id="f752f048f6ef445d8625f1710317620b"> What's the definition of object-oriented design? <a href="#f752f048f6ef445d8625f1710317620b" title="permalink">#</a> </h3> <p> Object-oriented design (OOD) has been around for decades; at least since the nineteen-sixties. Sometimes people get into discussions about whether or not a particular design is good object-oriented design. I know, since I've found myself in such discussions more than once. </p> <p> These discussions usually die out without resolution, because it seems that no-one can provide a sufficiently rigorous definition of OOD that enables people to determine an outcome. One thing's certain, though, so I'd like to posit this corollary to <a href="https://en.wikipedia.org/wiki/Godwin%27s_law">Godwin's law</a>: <blockquote> As a discussion about OOD grows longer, the probability of a comparison involving Alan Kay approaches 1. </blockquote> Not that I, in any way, wish to suggest any logical relationship between <a href="https://en.wikipedia.org/wiki/Alan_Kay">Alan Kay</a> and Hitler, but in a discussion about OOD, sooner or later someone states: <blockquote> "That's not what Alan Kay had in mind!" </blockquote> That may be true, even. </p> <p> My problem with that assertion is that I've never been able to figure out exactly what Alan Kay had in mind. It's something that involves message-passing and <a href="https://en.wikipedia.org/wiki/Smalltalk">Smalltalk</a>, and conceivably, the best modern example of this style of programming might be <a href="https://www.erlang.org">Erlang</a> (often, ironically, touted as a functional programming language). </p> <p> This doesn't seem to be a good basis for determining whether or not something is object-oriented. </p> <p> In any case, despite what Alan Kay had in mind, that wasn't the object-oriented programming we got. While <a href="https://en.wikipedia.org/wiki/Eiffel_(programming_language)">Eiffel</a> is in many ways a strange programming language, the philosophy of OOD presented in <a href="http://amzn.to/1claOin">Object-Oriented Software Construction</a> feels, to me, like something from which <a href="https://www.java.com">Java</a> could develop. </p> <p> I'm not aware of the detailed history of Java, but the spirit of the language seems more compatible with Bertrand Meyer's vision than with Alan Kay's. </p> <p> Subsequently, C# would hardly look the way it does had it not been for Java. </p> <p> The OOD we got wasn't the OOD originally envisioned. To make matters worse, the OOD we did get seems to be driven by unclear principles. Yes, there's the idea about encapsulation, but while Meyer had some very specific ideas about design-by-contract, that was the distinguishing trait of his vision that <em>didn't</em> make the transition to Java or C#. </p> <p> It's not clear what OOD is, but I think we can do better when it comes to functional programming (FP). </p> <h3 id="305ccccf2de84354bdb68b5b80d34fc9"> Referential transparency <a href="#305ccccf2de84354bdb68b5b80d34fc9" title="permalink">#</a> </h3> <p> It's possible to pinpoint what FP is to a degree not possible with OOD. Some people may be uncomfortable with the following definition; I don't claim that this is a generally accepted definition. It does have, however, the advantage that it's precise and supports <a href="https://en.wikipedia.org/wiki/Falsifiability">falsification</a>. </p> <p> The foundation of FP is <a href="https://en.wikipedia.org/wiki/Referential_transparency">referential transparency</a>. It's the idea that, for an expression, the left- and right-hand sides of the equal sign are truly equal: </p> <p> <pre>two = 1 + 1</pre> </p> <p> In <a href="https://www.haskell.org">Haskell</a>, this is enforced by the compiler. The <code>=</code> operator truly implies equality. To be clear, this isn't the case in C#: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;two&nbsp;=&nbsp;1&nbsp;+&nbsp;1;</pre> </p> <p> In C#, Java, and other imperative languages, the <code>=</code> implies <em>assignment</em>, not equality. Here, <code>two</code> can change, despite the absurdity of the claim. </p> <p> When code is referentially transparent, then you can substitute the expression on the right-hand side with the symbol on the left-hand side. This seems obvious when we consider addition of two numbers, but becomes less clear when we consider function invocation: </p> <p> <pre>i = findBestNumber [42, 1337, 2112, 90125]</pre> </p> <p> In Haskell, functions are referentially transparent. You don't know exactly what <code>findBestNumber</code> does, but you do know that you can substitute <code>i</code> with <code>findBestNumber [42, 1337, 2112, 90125]</code>, or vice versa. </p> <p> In order for a function to be referentially transparent (also known as a <a href="https://en.wikipedia.org/wiki/Pure_function">pure function</a>), it must have two properties: <ul> <li>It must always return the same output for the same input. We call this quality <em>determinism</em>.</li> <li>It must have no side effects.</li> </ul> As far as I can tell, all else in FP follows from this definition. For example, values must be immutable, because if they aren't, you could mutate them, and that would count as a side effect. </p> <p> The reason I prefer this definition is that it supports falsification. You can assert that a function or value is pure; all it takes is a single counter-example to prove that it's not. A counter-example can be either an input value that doesn't always produce the same return value, or a function call that produces a side effect. </p> <p> I'm not aware of any other definition that offers similar decision power. </p> <h3 id="43505c00cc25416db2b47a89912fd731"> IO <a href="#43505c00cc25416db2b47a89912fd731" title="permalink">#</a> </h3> <p> All software produces side effects: Changing a pixel on a monitor is a side effect. Writing a byte to disk is a side effect. Transmitting a bit over a network is a side effect. It seems that it'd be impossible to interact with pure functions, and indeed, it is, without some sort of affordance for impurity. </p> <p> Haskell resolves this problem with the <code>IO</code> monad, but the purpose of this article isn't to serve as an introduction to Haskell, monads, or <code>IO</code>. The point is only that in FP, you need some sort of 'wormhole' that will enable you to interact with the real world. There's no way around that, but logically, the rules still apply. Pure functions must stay deterministic and free of side effects. </p> <p> It follows that you have two groups of operations: impure activities and pure functions. </p> <p> <img src="/content/binary/impure-actions-pure-functions-no-arrows.png" alt="Two sets: the set of impure activities and the set of pure functions."> </p> <p> While there are rules for pure functions, those rules still allow for interaction. One pure function can call another pure function. Such an interaction doesn't change the properties of any of those functions. Both caller and callee remain side-effect-free and deterministic. </p> <p> <img src="/content/binary/impure-actions-pure-functions-pure-arrows.png" alt="Set of impure activities and set of pure functions. The pure functions now have arrows between them."> </p> <p> The impure activities can also interact. No rules apply to them: </p> <p> <img src="/content/binary/impure-actions-pure-functions-impure-and-pure-arrows.png" alt="Sets of impure activities and pure functions. Both sets now have internal arrows."> </p> <p> Finally, since no rules apply to impure activities, they can invoke pure functions: </p> <p> <img src="/content/binary/impure-actions-pure-functions-all-valid-arrows.png" alt="Sets of impure activities and pure functions, now also with arrows going from impure to pure."> </p> <p> Impure activities are unbound by rules, so they can do anything they need to do, including painting pixels, writing to files, or calling pure functions. A pure function is deterministic and has no side effects. Those properties don't change just because the result is subsequently displayed on a screen. </p> <p> The fourth combination of arrows is, however, illegal. <blockquote> A pure function can't invoke an impure activity. </blockquote> If it did, it would either transitively produce a side effect or non-deterministic behaviour. </p> <p> This is the rule of functional architecture. You can also explain it with a table: <table> <col> <col> <colgroup span="2"></colgroup> <thead> <tr> <td colspan="2" rowspan="2"></td> <th colspan="2" scope="colgroup">Callee</th> </tr> <tr> <th scope="col">Impure</th> <th scope="col">Pure</th> </tr> </thead> <tbody> <tr> <th rowspan="2" scope="rowgroup">Caller</th> <th scope="row">Impure</th> <td><span style="color:green">Valid</span></td> <td><span style="color:green">Valid</span></td> </tr> <tr> <th scope="row">Pure</th> <td><span style="color:red">Invalid</span></td> <td><span style="color:green">Valid</span></td> </tr> </tbody> </table> Let's call the above rule the <em>functional interaction law</em>: a pure function can't invoke an impure activity. A functional architecture, then, is a code base that obeys that law, and has a significant portion of pure code. </p> <p> Clearly, you can trivially obey the functional interaction law by writing exclusively impure code. In a sense, this is what you do by default in imperative programming languages. If you're familiar with Haskell, imagine writing an entire program in <code>IO</code>. That would be possible, but pointless. </p> <p> Thus, we need to add the qualifier that a significant part of the code base should consist of pure code. How much? The more, the better. Subjectively, I'd say significantly more than half the code base should be pure. I'm concerned, though, that stating a hard limit is as useful here <a href="http://blog.ploeh.dk/2015/11/16/code-coverage-is-a-useless-target-measure">as it is for code coverage</a>. </p> <h3 id="1009a90ea922424285e5f9a4bb30524e"> Tooling <a href="#1009a90ea922424285e5f9a4bb30524e" title="permalink">#</a> </h3> <p> How do you verify that you obey the functional interaction law? Unfortunately, in most languages the answer is that this requires painstaking analysis. This can be surprisingly tricky to get right. Consider this realistic F# example: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;createEmailNotification&nbsp;templates&nbsp;msg&nbsp;(user&nbsp;:&nbsp;UserEmailData)&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;{&nbsp;SubjectLine&nbsp;=&nbsp;subjectTemplate;&nbsp;Content&nbsp;=&nbsp;contentTemplate&nbsp;}&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;templates &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&gt;&nbsp;Map.tryFind&nbsp;user.Localization &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&gt;&nbsp;Option.defaultValue&nbsp;(Map.find&nbsp;Localizations.english&nbsp;templates) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;r&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Templating.append &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(Templating.replacementOfEnvelope&nbsp;msg) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(Templating.replacementOfFlatRecord&nbsp;user) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;subject&nbsp;=&nbsp;Templating.run&nbsp;subjectTemplate&nbsp;r &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;content&nbsp;=&nbsp;Templating.run&nbsp;contentTemplate&nbsp;r &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;RecipientUserId&nbsp;=&nbsp;user.UserId &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;EmailAddress&nbsp;=&nbsp;user.EmailAddress &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;NotificationSubjectLine&nbsp;=&nbsp;subject &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;NotificationText&nbsp;=&nbsp;content &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CreatedDate&nbsp;=&nbsp;DateTime.UtcNow &nbsp;&nbsp;&nbsp;&nbsp;}</pre> </p> <p> Is this a pure function? </p> <p> You may protest that this isn't a fair question, because you don't know what, say, <code>Templating.replacementOfFlatRecord</code> does, but that turns out to be irrelevant. The presence of <code>DateTime.UtcNow</code> makes the entire function impure, because getting the current date and time is non-deterministic. This trait is transitive, which means that any code that calls <code>createEmailNotification</code> is also going to be impure. </p> <p> That means that the purity of an expression like the following easily becomes obscure. </p> <p> <pre><span style="color:blue;">let</span>&nbsp;emailMessages&nbsp;=&nbsp;specificUsers&nbsp;|&gt;&nbsp;Seq.map&nbsp;(createEmailNotification&nbsp;templates&nbsp;msg)</pre> </p> <p> Is this a pure expression? In this case, we've just established that <code>createEmailNotification</code> is impure, so that wasn't hard to answer. The problem, however, is that the burden is on you, the code reader, to remember which functions are pure, and which ones aren't. In a large code base, this soon becomes a formidable endeavour. </p> <p> It'd be nice if there was a tool that could automatically check the functional interaction law. </p> <p> This is where many people in the functional programming community become uncomfortable about this definition of functional architecture. The only tools that I'm aware of that enforce the functional interaction law are a few programming languages, most notably Haskell (others exist, too). </p> <p> Haskell enforces the functional interaction law via its <code>IO</code> type. You can't use an <code>IO</code> value from within a pure function (a function that doesn't return <code>IO</code>). If you try, your code doesn't compile. </p> <p> I've personally used Haskell repeatedly to understand the limits of functional architecture, for example to establish that <a href="http://blog.ploeh.dk/2017/01/30/partial-application-is-dependency-injection">Dependency Injection isn't functional</a> because it makes everything impure. </p> <p> The overall lack of tooling, however, may make people uncomfortable, because it means that most so-called functional languages (e.g. F#, Erlang, <a href="https://elixir-lang.org/">Elixir</a>, and <a href="https://clojure.org">Clojure</a>) offer no support for validating or enforcing functional architecture. </p> <p> My own experience with writing entire applications in F# is that I frequently, inadvertently violate the functional interaction law somewhere deep in the bowels of my code. </p> <h3 id="8e33b2ffd51f46f18e38c5add37f1728"> Conclusion <a href="#8e33b2ffd51f46f18e38c5add37f1728" title="permalink">#</a> </h3> <p> What's functional architecture? I propose that it's code that obeys the functional architecture law, and that is made up of a significant portion of pure functions. </p> <p> This is a narrow definition. It excludes a lot of code bases that could easily be considered 'functional enough'. By the definition, I don't intend to denigrate fine programming languages like F#, Clojure, Erlang, etcetera. I personally find it a joy to write in F#, which is my default language choice for .NET programming. </p> <p> My motivation for offering this definition, albeit restrictive, is to avoid the OOD situation where it seems entirely subjective whether or not something is object-oriented. With the functional interaction law, we may conclude that most (non-Haskell) programs are probably not 'really' functional, but at least we establish an falsifiable ideal to strive for. </p> <p> This would enable us to look at, say, an F# code base and start discussing <em>how close to the ideal is it?</em> </p> <p> Ultimately, functional architecture isn't a goal in itself. It's a means to achieve an objective, such as a sustainable code base. I find that FP helps me keep a code base sustainable, but often, 'functional enough' is sufficient to accomplish that. </p> </div> <div id="comments"> <hr /> <h2 id="comments-header">Comments</h2> <div class="comment" id="ccf908a42b644b8b9bb2bf6bcbc25052"> <div class="comment-author"> <a href="https://github.com/MaxKot">Max Kiselev</a> </div> <div class="comment-content"> <p> Good idea of basing the definition on falsifiability! </p> <p> The createEmailNotification example makes me wonder though. If it is not a functional design, then what design it actually is? I mean it has to be some design and it does not looks like object-oriented or procedural one. </p> </div> <div class="comment-date">2018-11-20 21:36 UTC</div> </div> <div class="comment" id="6a4ca5d3da3e4a63a413982f589c384c"> <div class="comment-author"><a href="http://blog.ploeh.dk">Mark Seemann</a></div> <div class="comment-content"> <p> Max, thank you for writing. I'm not sure whether the assertion that it <em>has</em> to be some design or other is axiomatically obvious, but I suppose that we humans have an innate need to categorise things. </p> <p> Don Syme calls F# a <em>functional-first</em> language, and that epithet could easily apply to that style of programming as well. Other options could be <em>near-functional</em>, or perhaps, if we're in a slightly more academic mood, <em>quasi-functional</em>. </p> <p> In daily use, we'd probably still call code like that <em>functional</em>, and I don't think it'll cause much confusion. </p> <p> If I remember the history of programming correctly, the first attempts at functional programming didn't focus on referential transparency, but simply on the concept of functions as first-class language features, including lambda expressions and higher-order functions. The little I know of <a href="https://en.wikipedia.org/wiki/Lisp_(programming_language)">Lisp</a> corroborates that view on the history of functional programming. </p> <p> Only later (I think) did languages appear that make compile-time distinction between pure and impure code. </p> <p> My purpose with this article wasn't to exclude a large number of languages or code bases from being functional, but just to offer a falsifiable test that we can use for evaluation purposes, if we're ever in doubt. This is something that I feel is sorely missing from the object-oriented debate, and while I can't think of a way to remedy the OOD situation, I hope that the present definition of functional architecture presents firmer ground upon which to have a debate. </p> </div> <div class="comment-date">2018-11-21 6:42 UTC</div> </div> <div class="comment" id="902887b4a1954daf8be09e35ce685fbb"> <div class="comment-author"><a href="https://github.com/wachulski">Marcin Wachulski</a></div> <div class="comment-content"> <p> Thank you for your definition that forms good grounds for reasoning about functional property of code. I remember some people say that even C# is functional as it allows for <em>delegates</em>. Several thoughts: </p> <p> 1. Remember <a href="https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.contracts.pureattribute?view=netcore-2.1">[Pure]</a> attribute and CodeContracts? It aided the purpose of defensive programming to hold pre/postconditions and invariants. I have this impression that both functional purity and defensive programming help us find ad-hoc quasi-mathematical proofs of code correctness after we load a codebase to our heads. It's way easier then to presume how it works and make changes. Of course it's not mathematical in the strict sense, but still - we tend to trust the code more (e.g. threading). I'm pretty sure unit tests belong to this family too. </p> <p> 2. Isn't the purity concept anywhere close to gateways (code that crosses the boundaries of program determinism control zone, e.g. IO, time, volatile memory)? It's especially evident while refactoring legacy code to make it unit testable. We often extract out infrastructure dependent parts (impure activities, e.g. DateTime.Now) for the other be deterministic (pure) and hence - testable. </p> <p> 3. Can the whole program/system be as pure as this: <pre>INPUT -> PURE_CODE -> OUTPUT</pre> I'm afraid not as it'd mean the pure code needed to know all the required input data upfront. That's impossible most of times. So, when it comes to measures, I'd argue that the number of pure code lines is enough to tell how pure the codebase is. I'd accompany this with e.g. percentile distribution of pure chunk length (functions/blocks of contingent im/purity etc.). E.g. I'd personally favour 1) over 2) in the following: <pre> 1. INPUT -> 3 x LONG_PURE_CHUNK + 2 x LONG_IMPURE_CHUNK -> OUTPUT 2. INPUT -> 10 x SHORT_PURE_CHUNK + 7 x SHORT_IMPURE_CHUNK -> OUTPUT </pre> </p> <p> 4. I'd love to see such tools too :) I believe the purity concept does not pertain only to FP nor OO and is related to the early foundational days of computer programming with mathematical proofs they had. </p> </div> <div class="comment-date">2018-11-23 10:51 UTC</div> </div> <div class="comment" id="82b14ead068b42698186710ba7bcf145"> <div class="comment-author"><a href="http://blog.ploeh.dk">Mark Seemann</a></div> <div class="comment-content"> <p> Marcin, thank you for writing. To be clear, you can perform side effects or non-deterministic behaviour in C# delegates, so delegates aren't guaranteed to be referentially transparent. In fact, <a href="http://blog.ploeh.dk/2018/01/22/function-isomorphisms">delegates, and particularly closures, are isomorphic to objects</a>. In C#, <a href="http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional">they even compile to classes</a>. </p> <p> I'm aware that some people think that they're doing functional programming when they use lambda expressions in C#, but I disagree. </p> <p> I'll see if I can address your other comments below. </p> <h3 id="c085eef3102d437ba9c6cbe3363b8976"> Re: 1. <a href="#c085eef3102d437ba9c6cbe3363b8976" title="permalink">#</a> </h3> <p> Some functions are certainly ad-hoc, while <a href="http://blog.ploeh.dk/2017/10/04/from-design-patterns-to-category-theory">others are grounded in mathematics</a>. I agree that pure functions 'fit better in your brain', mostly because it's clear that the only stimuli that can affect the outcome of the function is the input. Granted, if we imagine a concrete, ad-hoc function that takes 23 function arguments, we might still consider it bad code. Small functions, though, tend to be easy to reason about. </p> <p> I've previously written about the <a href="http://blog.ploeh.dk/2016/02/10/types-properties-software">relationship between types and tests</a>, and I believe that there's some sort of linearity in that relationship. The better the type system, the fewer tests you need. The weaker the type system, the more tests you need. It's no wonder that the unit testing culture related to languages like Ruby seems stronger than in the Haskell community. </p> <h3 id="405184fce774458ba8d3484c2580f322"> Re: 2. <a href="#405184fce774458ba8d3484c2580f322" title="permalink">#</a> </h3> <p> In my experience, most people make legacy code more testable by introducing some variation of Dependency Injection. This may enable you to control some otherwise non-deterministic behaviour from tests, but <a href="http://blog.ploeh.dk/2017/01/27/from-dependency-injection-to-dependency-rejection">it doesn't make the design more functional</a>. Those types of dependencies (e.g. on <code>DateTime.Now</code>) are inherently impure, and therefore they make everything that invokes them impure as well. The above <em>functional interaction law</em> excludes such a design from being considered functional. </p> <p> <a href="http://blog.ploeh.dk/2015/05/07/functional-design-is-intrinsically-testable">Functional code, on the other hand, is intrinsically testable</a>. Watch out for a future series of articles that show how to move an object-oriented architecture towards something both more functional, more sustainable, and more testable. </p> <h3 id="5201a19bec7b413ebb6e7ca3e2dfbc81"> Re: 3. <a href="#5201a19bec7b413ebb6e7ca3e2dfbc81" title="permalink">#</a> </h3> <p> A command-line utility <em>could</em> be as pure as you suggest, but most other programs will need to at least <ol> <li>load some more data from impure sources, such as files, databases, or the current time,</li> <li>run some pure functions,</li> <li>output the results to some impure destinations, such as files, databases, UI, email, and so on.</li> </ol> I call this type of architecture a <a href="http://blog.ploeh.dk/2017/02/02/dependency-rejection">pure-impure-pure sandwich</a>, and you can <a href="http://blog.ploeh.dk/2017/07/10/pure-interactions">often, but not always, structure your application code in that way</a>. </p> <h3 id="e8befe231edf474899477eb39074d8d0"> Re: 4. <a href="#e8befe231edf474899477eb39074d8d0" title="permalink">#</a> </h3> <p> I'm not sure I understand what you mean by that comment, but the mathematical proofs about computability pre-date computer programming. Gödel's work on recursive functions is from 1933, Church's work on lambda calculus is from 1936, and Turing's paper <em>On Computable Numbers, with an Application to the Entscheidungsproblem</em> is from later in 1936. Turing and Church later showed that <a href="https://en.wikipedia.org/wiki/Church%E2%80%93Turing_thesis">all three definitions of computability are equivalent</a>. </p> <p> I don't know much about Gödel's work, but lambda calculus is defined entirely on the foundation of <em>functions</em>, while the Turing machines described in Turing's paper have nothing to do with functions in the mathematical sense. </p> <p> Mathematical functions are, however, referentially transparent. They're also <em>total</em>, meaning that they always return a result for any input in the function's domain. Due to the halting problem, a Turing-complete language can't guarantee that all functions are total. </p> </div> <div class="comment-date">2018-11-24 9:04 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please consider <a href="http://blog.ploeh.dk/support">supporting it</a>. 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 consider <a href="http://blog.ploeh.dk/support">supporting it</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> <a href="http://blog.ploeh.dk/2018/11/26/the-test-data-generator-applicative-functor">The Test Data Generator applicative functor</a>. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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><a href="http://blog.ploeh.dk/2018/11/26/the-test-data-generator-applicative-functor">The Test Data Generator applicative functor</a></li> <li><a href="http://blog.ploeh.dk/2018/12/10/danish-cpr-numbers-in-f">Danish CPR numbers in F#</a></li> <li><a href="http://blog.ploeh.dk/2018/12/17/the-lazy-applicative-functor">The Lazy applicative functor</a></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 consider <a href="http://blog.ploeh.dk/support">supporting it</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/12/03/set-is-not-a-functor">Set is not a functor</a>. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 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#. 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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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 consider <a href="http://blog.ploeh.dk/support">supporting it</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<