<?xml version="1.0" encoding="UTF-8" standalone="no"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" version="2.0">

<channel>
	<title>Pirrmann's train of thought</title>
	<atom:link href="http://www.pirrmann.net/feed/" rel="self" type="application/rss+xml"/>
	<link>http://www.pirrmann.net</link>
	<description>Pierre Irrmann on coding, and how fun it is, even in the train</description>
	<lastBuildDate>Mon, 12 Dec 2016 10:55:45 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<xhtml:meta content="noindex" name="robots" xmlns:xhtml="http://www.w3.org/1999/xhtml"/><item>
		<title>Some advice to F# beginners</title>
		<link>http://www.pirrmann.net/some-advice-to-f-beginners/</link>
		<comments>http://www.pirrmann.net/some-advice-to-f-beginners/#comments</comments>
		<pubDate>Mon, 12 Dec 2016 09:43:17 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[F sharp love]]></category>
		<category><![CDATA[Practices]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[FsAdvent]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=282</guid>
		<description><![CDATA[This post is part of the F# Advent Calendar in English 2016 project. Check out all the other great posts there! And special thanks to Sergey Tihon for organizing this. I’m very happy that F# is getting used more and &#8230; <a href="http://www.pirrmann.net/some-advice-to-f-beginners/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<blockquote><p align="justify">This post is part of the <a href="https://sergeytihon.wordpress.com/2016/10/23/f-advent-calendar-in-english-2016/">F# Advent Calendar in English 2016</a> project. Check out all the other great posts there! And special thanks to Sergey Tihon for organizing this.</p>
</blockquote>
<p align="justify"><img style="float: right; margin: 0px 0px 10px 10px; display: inline" src="http://www.pirrmann.net/wp-content/uploads/2016/12/fsharp-is-good-for-you.jpg" width="250" align="right">I’m very happy that F# is getting used more and more in my work place. It has even got to a point where some code has been written a while ago and maintenance is done by someone who hasn’t been involved in the project at all in the beginning. This has been an chance to work on a somewhat “legacy” F# code, which was the first time for me. The code on which we’ve worked had been written by someone who was a well-grounded C# dev, but not fluent in F#. Let’s say that the produced F# code is not very idiomatic. After going through this code, here is some advice I’d like to give to beginners.</p>
<blockquote><p>Disclaimer: I’m talking about regular code here, there is no particular constraint on performance nor memory (this is not real-time nor high-frequency trading). We can afford to allocate memory and trigger GC collections. The advice given here may not be relevant to your specific use-case.</p>
</blockquote>
<h2>Type all the things</h2>
<p align="justify">While gradually building something in F#, you’ll probably use tuples, because they’re so easy to use. And when writing a function, adding a new parameter is really easy, so of course you’ll do. However, if you keep doing that, you end up with code that’s difficult to maintain. The classical answer in a statically typed functional language for such a problem is “add more types”.</p>
<p align="justify">If you find yourself using:</p>
<ol>
<li>tuples with too many items in it: use a type to name your items (a record for instance)<br /> 
<li>record types with too many properties: compose smaller types to group related properties
<li>higher-order functions: define a type for each non-trivial function signature you consume or return
<li>functions with too many arguments: group arguments with types (but still remember points 1 &amp; 2)</li>
</ol>
<h2>Keep things simple</h2>
<p align="justify">This applies to any language, and is not F# specific. However when some people start to “get” how F# works, they tend to over-complicate things, where they could have been kept simple. <em>Don’t forget the common sense good practices that apply to other languages</em>, just because you’re coding in F#. <a href="http://fsprojects.github.io/FSharpLint/">FSharpLint</a> (available as part of <a href="https://fsprojects.github.io/VisualFSharpPowerTools/">F# Power Tools</a>) is a tool that can help you with that. In particular, it enforces the use of:</p>
<ul>
<li>small functions
<li>even smaller lambdas
<li>small tuples only (4 items max, and I’d say 4 is already too much)</li>
</ul>
<h2>Piping</h2>
<p align="justify">Piping is super cool. I acknowledge that. In my opinion, it allows you to easily express the “flow” of data through steps, and is very expressive. However that doesn’t mean you should go crazy with pipes.</p>
<p align="justify">Piping into 10 steps of complicated filters, grouping, and folds, is not as readable after 6 months as you thought it was when you were writing it. Comments could help, but defining steps in named variables, and composing them in the end, is very easy to do and will allow you to express the intent directly in the code.</p>
<h2>Curried functions</h2>
<p align="justify">Curried functions only make sense if you can do partial applications that also make sense. If your arguments don’t make any sense if they’re not provided together, they compose a single unit of meaningful data, and you should:</p>
<ul>
<li>either group those items in a tuple,
<li>or (most probably) define a type.</li>
</ul>
<h2>Higher-order functions</h2>
<p align="justify">“Higher-order” means that at least one parameter of the function is going to be a function itself. Why not? Functions are first-class citizens. However, don’t try to be too smart. Remember, “Keep things simple”. Taking functions as parameter is one thing, but taking <em>higher-order functions</em> as parameters starts to become complicated. There can probably be cases where it makes sense, but don’t overuse it. And if you need to take functions as parameters, consider defining meaningful types for theses function signatures.</p>
<h2>Explicit side-effects</h2>
<p align="justify">F# is not a pure functional language, as it doesn’t prevent you from mutating state or having side-effects in your code. However, when you write a function that has side effects, make it as explicit as you can. Don’t hide a function that has side effects in the middle of a call chain, unless it is obvious from the caller standpoint that the call is intended to have side effects. F# type system will not prevent you from such things, so you’ll need a bit of discipline there.</p>
<h2>Tests</h2>
<p align="justify">Writing tests in F# is supposed to be easy. When you write tests, you shouldn’t have to build a big context for each test. If you’ve kept your types and functions simple, your unit tests will not have many dependencies or boilerplate setup. Composition is what functional programming is really about. As soon as your tests feels like wiring things up instead of validating your code behaviour, stand back and try to see if concerns can be separated.</p>
<h2>Conventions &amp; whitespaces</h2>
<p align="justify">I do get that it’s not easy to choose a convention and stay consistent when you’re new to a language, but having a consistent convention regarding spaces makes your code much more pleasant to read (or maybe it’s just me and my OCD). Please do.</p>
<h2>Dependencies</h2>
<p align="justify">Switching to a new language doesn’t mean you should forget everything you’ve learned so far. For instance, the Single responsibility principle is still a good practice! You can think of a function signature as an interface with a single method on it. When you provide a function as a parameter, it’s like injecting the implementation of an interface. Whenever you do it, you should ask yourself whether you really want to inject it. <em>“Do you want to inject a database access function there, or do you want to perform the call somewhere else and just pass in the returned data to the function?”</em>. Every function parameter can be considered a dependency.</p>
<h2>Write (or don’t, actually) your own DSLs, Computation expressions, and Type providers</h2>
<p align="justify">Don’t do that in the first week! I’m totally guilty of using fun and cool features just because I think they’re amazing (and sometimes I want to show off), but try to get the basics right first…</p>
<ul>
<li>
<div align="justify">DSLs will only prove useful if they’re built on top of well-thought abstractions. Trying to build the DSL first, in order to have a user-friendly readable code, can also lead to overcomplicated implementation underneath.</div>
<li>
<div align="justify">Computation expressions are just syntactic sugar over abstractions. You can probably achieve the same result without them. Try to get your types and concepts right before you find yourself trying to use the “<em>MaintainsVariableSpaceUsingBind</em>” property on a <em>CustomOperationAttribute</em>.</div>
<li>
<div align="justify">Type providers (erased ones, at least) are usually also only syntactic sugar that helps ensure type-safety and convenience. Before writing your own, consider using a simpler approach (but it definitely can make sense to write your own, and if you ever need, you can ping me!)</div>
</li>
</ul>
<p><em>The advice given here may seem too simplistic, but it can’t hurt, can it?</em></p>
<p><em>PS: Now I understand the imposter syndrome</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/some-advice-to-f-beginners/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Making program behaviour explicit</title>
		<link>http://www.pirrmann.net/making-program-behaviour-explicit/</link>
		<comments>http://www.pirrmann.net/making-program-behaviour-explicit/#comments</comments>
		<pubDate>Thu, 31 Mar 2016 22:38:45 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[F sharp love]]></category>
		<category><![CDATA[Syntax Puzzles]]></category>
		<category><![CDATA[Computation Expressions]]></category>
		<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=272</guid>
		<description><![CDATA[When observing developers in their day-to-day work, it’s quite usual to see them swearing at their programs, because they don’t behave as they should. You often see them asking the program to obey, sometimes cursing, and even praying from time &#8230; <a href="http://www.pirrmann.net/making-program-behaviour-explicit/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p align="justify"><img style="float: right; margin: 0px 0px 10px 10px; display: inline" src="http://www.pirrmann.net/wp-content/uploads/2016/04/FSM.jpg" width="400" align="right" height="206">When observing developers in their day-to-day work, it’s quite usual to see them swearing at their programs, because they don’t behave as they should. You often see them asking the program to obey, sometimes cursing, and even praying from time to time. If we take some time to think about it, the main reason why a programmer shouts at a running program is because it doesn’t quite behave as he/she wants it to do. Unfortunately, this is less common in the functional programming community. Having a language that promotes usage of immutability and option types (to name only a few), sometimes deprives you of cursing and praying.</p>
<p align="justify">Fortunately, F# has a feature called computation expressions, that can bring you back the joy of an unpredictable behaviour at runtime! I hope you’ll enjoy the ones I’m going to introduce today. For instance, they allow you to write the following code:</p>
<div>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let theAnswer = usually { return 42 }
let basicArithmetic = mostProbably { return 6 * 7 }</pre>
</div>
<p align="justify">As those samples clearly state, they <em>usually</em> and <em>mostProbably</em> behave as expected. However, they sometimes do slightly different things. Indeed, the computation expressions are sometimes mutated, and then evaluate to something else. Using this, you can cause <em>subtle bugs</em>, that <em>only occur from time to time</em>, deep inside more complex computations. And as you can expect, the debugging experience will be completely awful.</p>
<p align="justify">That’s a nice first step. But didn’t I mention cursing an praying? Stay tuned. Using a combination of custom operations and mutable state (ouch!), this is perfectly valid code:</p>
<div>
<pre class="brush: fsharp; gutter: false; toolbar: false;">pray God {
    // This begins a safe section
    ``The lord is my shepherd``
    let x = 6
    ``He led me in the paths of righteousness``
    // Here the safe section is over

    let y = 55

    // this is just another safe section
    ``Whoever walks in integrity walks securely``
    let z = 2
    ``But whoever takes crooked paths will be found out``
    // And here the safe section ends

    // This starts a perilous section
    ``I walk through the valley of the shadow of death``

    return (y * z + 1) * x
}</pre>
</div>
<p align="justify">And it comes in different flavours, you can pray your own favourite god if you wish:</p>
<div>
<pre class="brush: fsharp; gutter: false; toolbar: false;">pray FlyingSpaghettiMonster {
    ``I believe Thou art the Creator of Goodness and Nourishment``
    let x = 1
    ``I believe that Thou are neither Male, nor Female``
    let y = 2
    ``I thank Thee for the giving of healthful Green Salad``
    let z = 3
    ``R'amen``
    return x + y - z
}</pre>
</div>
<p align="justify">In the previous samples, you compose a prayer, that will change the mood of the god who listens to it:</p>
<ul>
<li>in the default state, there is a small chance that mutation occur in the expressions,
<li>when the god is pleased, the code is safe and no mutation occurs,
<li>when the god is angry, expect numerous mutations.</li>
</ul>
<p align="justify">Of course, using a sentence which is not intended for the right god will trigger mutations.</p>
<p align="justify">So how do we build this? Computation expressions are in most cases just used as syntactic sugar that allows you to bind continuation functions to a given state (as very well explained <a href="https://fsharpforfunandprofit.com/series/computation-expressions.html">on fsharpforfunandprofit</a>). But you can also use computation expressions to get a <a href="https://msdn.microsoft.com/en-US/library/dd233212.aspx">quotation</a> of the expression. This is what’s behind the <a href="http://mbrace.io/programming-model.html#Cloud-Workflows">cloud expression offered by MBrace</a>.</p>
<p align="justify">Once given an expression, you can manipulate it to build a new derived expression. In the end, in order to evaluate the expression, I’ve used the evaluator packaged in <a href="http://www.swensensoftware.com/unquote">Unquote</a>. In the end, the computation expression builder class is almost empty:</p>
<div>
<pre class="brush: fsharp; gutter: false; toolbar: false;">type ChaosBuilder (mutationSitePicker:IMutationSitePicker,
                   expressionReplacer:IExpressionReplacer) =
    member this.Return(x) = x
    member this.Quote (expr) = expr
    member this.Run (expr:Expr&lt;'T&gt;) =
        let choaticExpr =
            mutate mutationSitePicker expressionReplacer expr
        choaticExpr.Eval&lt;'T&gt;()</pre>
</div>
<p align="justify">The IMutationSitePicker is responsible for choosing a site, ant the IExpressionReplacer actually performs the expression maniputation. Here is a sample implementation that give every eligible expression a random chance to be replaced:</p>
<div>
<pre class="brush: fsharp; gutter: false; toolbar: false;">type MutateWithProbability(proportion) =
    let r = new System.Random()
    let mutable lastRandom = r.NextDouble()
    interface IMutationSitePicker with
       member this.PickNextSite = lastRandom &lt; proportion
       member this.NotifyIgnoredSite() = lastRandom &lt;- r.NextDouble()
       member this.NotifyMutation() = lastRandom &lt;- r.NextDouble()</pre>
</div>
<p align="justify">I’m not going to include the actual expression manipulation code here, but my current work on this very valuable feature is <a href="https://gist.github.com/pirrmann/aeef0b53362e84abe4ca9c1f69485c8e">available as a Gist</a>. Implementing computation expressions which allow (and encourage) cursing is left as an exercise to the reader.</p>
<p align="justify">Some of the code used here could actually be used to perform <a href="https://en.wikipedia.org/wiki/Mutation_testing">mutation testing</a>. the only replacement implemented so far is numeric constants mutation, but there are many other kinds of fun mutations to add (see <a href="http://web.engr.oregonstate.edu/~alipourm/pub/fp_mutation.pdf">Mutation Testing of Functional Programming Languages</a> for instance) such as “replacing an arithmetic, relational, logical, bitwise logical […] operator by another of the same class”, “Reordering Pattern Matching”, and even “Type-aware Function Replacement”.</p>
<p>As a conclusion, I want to say that even if I often abuse computation expressions to do stupid things, they’re a really powerful feature of the F# language and really allow to write cool DSLs.</p>
<p>EDIT: I’ve implemented the arithmetic operator replacement in the train this morning, the gist has been updated.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/making-program-behaviour-explicit/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Visualizing F# Advent Calendar contributors</title>
		<link>http://www.pirrmann.net/visualizing-f-advent-calendar-contributors/</link>
		<comments>http://www.pirrmann.net/visualizing-f-advent-calendar-contributors/#comments</comments>
		<pubDate>Sun, 27 Dec 2015 23:00:01 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[F sharp love]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[FsAdvent]]></category>
		<category><![CDATA[Functional programming]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=263</guid>
		<description><![CDATA[This post is part of the F# Advent Calendar in English 2015 project. Check out all the other great posts there! And special thanks to Sergey Tihon for organizing this. A few weeks ago, while at BuildStuff, I walked next &#8230; <a href="http://www.pirrmann.net/visualizing-f-advent-calendar-contributors/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<blockquote><p align="justify">This post is part of the <a href="https://sergeytihon.wordpress.com/2015/10/25/f-advent-calendar-in-english-2015/">F# Advent Calendar in English 2015</a> project. Check out all the other great posts there! And special thanks to Sergey Tihon for organizing this.</p>
</blockquote>
<p align="justify">A few weeks ago, while at BuildStuff, I walked next to an image built with words, like a tag cloud picturing some company’s logo. My first reaction was: “That looks nice, but has someone been paid to manually placed all these words? I bet it can be automated…”</p>
<p align="justify">I started putting together a script, in order to fill an image with words. My first attempt had disastrous performance and memory characteristics. Several hours of work later (quite a few, actually), and with contributions from my co-workers, we ended-up with a much better algorithm.</p>
<p align="justify">F# is a wonderful language to experiment with ideas. The convenience of quickly defining types with almost no ceremony lets you focus on what you’re really trying to build. The power of the .NET ecosystem lets you use all the standard APIs that you expect to find on a serious platform. This is really enjoyable and helps you to build simple things first, and evolve to more complicated ones while staying focused.</p>
<p>In the end we’re able to produce images such as:</p>
<p><a href="http://www.pirrmann.net/wp-content/uploads/2015/12/buildstuff.png"><img style="float: none; margin: 0px auto; display: block" src="http://www.pirrmann.net/wp-content/uploads/2015/12/buildstuff.png" width="450"></a></p>
<p align="justify">In order to produce such an image, we need an image to use as the model, and a list of words to fill the shape with. We had much fun doing it, both trying to identify strategies to make the images look good and get the generation time down. You can find the full source code on Github: <a title="https://github.com/pirrmann/Wordz" href="https://github.com/pirrmann/Wordz">https://github.com/pirrmann/Wordz</a></p>
<h3>The goal: build a nice picture</h3>
<p align="justify">Another area where F# shines is related to getting data from various sources and manipulate it. This enables so many scenarios. What if we could get pictures, and related text, from some place such as <a title="https://sergeytihon.wordpress.com/2015/10/25/f-advent-calendar-in-english-2015/" href="https://sergeytihon.wordpress.com/2015/10/25/f-advent-calendar-in-english-2015/">https://sergeytihon.wordpress.com/2015/10/25/f-advent-calendar-in-english-2015/</a> for instance, and generate all sorts of images?</p>
<h3>Step 1: parse the the posts list</h3>
<p align="justify">I’m happy <a href="https://twitter.com/TeaDrivenDev">@TeaDrivenDev</a> hasn’t published his first post idea about generating the RSS feed from the FsAdvent page, because I also have to parse the page in order to get my data… so first thing, we need to get the posts URLs from the page. It gives me a chance to mention the HTML Type Provider, which is part of the <a href="http://fsharp.github.io/FSharp.Data/">FSharp.Data library</a>. Accessing the list of posts and downloading all the posts is as easy as:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">type adventCalendarPage =
    HtmlProvider&lt;"https://sergeytihon.wordpress.com/[...]/"&gt;
type PageRow =
    adventCalendarPage.FAdventCalendarInEnglish2015.Row

let postsTable =
    adventCalendarPage
        .GetSample()
        .Tables
        .``F# Advent Calendar in English 2015``

let extractPostsLinks (tr:HtmlNode) =
    let lastTd = tr.Elements("td") |&gt; Seq.last

    lastTd.Elements("a")
    |&gt; List.map (fun a -&gt; a.AttributeValue("href"))

let postLinks =
    postsTable.Html.Descendants("tr")
    |&gt; Seq.tail
    |&gt; Seq.map extractPostLinks

let downloadPostsAsync links = 
    links
    |&gt; Seq.map HtmlDocument.AsyncLoad
    |&gt; Async.Parallel

let postsDownloads =
    postLinks
    |&gt; Seq.map downloadPostsAsync
    |&gt; Async.Parallel
    |&gt; Async.RunSynchronously

let allPosts = Array.zip postsTable.Rows postsDownloads</pre>
</div>
<p align="justify">From the previous sample, you may notice how the HTML type provider also allows you to access the elements of the page through the DOM. This is quite representative of how a good library design gracefully lets you use the underlying technology when the high-level API doesn’t suit your needs.</p>
<h3>Step 2: extract words</h3>
<p align="justify">We have now obtained all published FsAdvent posts in the form of HtmlDocument objects, but we don’t have their content yet… No magic type provider here, all posts are hosted on different blogging platforms, I had to use several strategies and fallbacks to identify the HTML element containing the post in each case. Semantic web is really not there yet! The search function finally looks like this:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let search =
    findDivWithEntryClassUnderDivWithPostClass
    |&gt; fallback findWintellectContent
    |&gt; fallback findDivWithClassStoryContent
    |&gt; fallback findArticle
    |&gt; fallback findElementWithClassOrIdPost
    |&gt; fallback findH1TitleParentWithEnoughContent
    |&gt; fallback findScottwContent
    |&gt; fallback findMediumContent
    |&gt; fallback wholePageContent</pre>
</div>
<p align="justify">The next step of interest is how to extract the most important words from each post. Another handy feature of F# are computation expressions, and in particular the built-in ones such as async an seq. Returning a sequence while recursively traversing a tree is as easy as:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let getMultiplier (node:HtmlNode) =
    match node.Name() with
    | "h1" -&gt; 16 | "h2" -&gt; 12 | "h3" -&gt; 8
    | "h4" -&gt; 4  | "h5" -&gt; 3  | "h6" -&gt; 2
    | _ -&gt; 1

let rec collectAllWords multiplier (node:HtmlNode) = seq {
    match node.Elements() with
    | [] -&gt;
        let text = node.InnerText()
        let words =
            text.Split(delimiters)
            |&gt; Seq.filter (not &lt;&lt; String.IsNullOrWhiteSpace)
            |&gt; Seq.filter (fun s -&gt; s.Length &gt; 1)
            |&gt; Seq.map (fun s -&gt; s.ToLowerInvariant())
        for word in words do
            if not(filteredWords.Contains word) then
                yield word, multiplier

    | children -&gt;
        let multiplier' = getMultiplier node
        yield! children
               |&gt; Seq.collect (collectAllWords multiplier')
}</pre>
</div>
<p align="justify">The last step once we’ve obtained all the words from each post with is to group them and sum their weight in order to get an indicator of their importance in the post. We define a function for that:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let sumWeights words =
    words
    |&gt; Seq.groupBy fst
    |&gt; Seq.map (fun (word, weights) -&gt; word,
                                       weights |&gt; Seq.sumBy snd)
    |&gt; Seq.sortByDescending snd
    |&gt; Seq.take 100
    |&gt; Seq.toList</pre>
</div>
<h3>Step 3: get Twitter profile pictures</h3>
<p align="justify">So we have all words from the FsAdvent posts published so far, and their relative importance in each post. But in order to create a visualization, we need model images, right? Let’s download the Twitter profile pictures of the authors! The profile urls can be extracted from the FsAdvent page (actually some of them are not links to twitter, so I had to cheat a bit, and this is why the function extractCleanLink is omitted…)</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let extractProfileLink (tr:HtmlNode) =
    let lastTd = tr.Elements("td") |&gt; Seq.item 1
    let a = lastTd.Elements("a") |&gt; Seq.head
    a.InnerText(), a.AttributeValue("href")

let profilesLinks =
    postsTable.Html.Descendants("tr")
    |&gt; Seq.tail
    |&gt; Seq.map extractProfileLink

let downloadAndSavePictureAsync (name:string, twitterProfileUrl:string) = async {
    let fileName = getFileName "profiles" name

    let cookieContainer = new Net.CookieContainer()

    let! twitterProfileString = Http.AsyncRequestString(twitterProfileUrl,
                                                        cookieContainer = cookieContainer)
    let twitterProfile = HtmlDocument.Parse(twitterProfileString)

    let profileImageLink =
        twitterProfile.Descendants("a")
        |&gt; Seq.find(fun a -&gt; a.HasClass("ProfileAvatar-container"))
            
    let profilePictureUrl = profileImageLink.AttributeValue("href")

    let! imageStream = Http.AsyncRequestStream profilePictureUrl

    use image = Image.FromStream(imageStream.ResponseStream)
    image.Save(fileName, Imaging.ImageFormat.Png)

    return () }

profilesLinks
|&gt; Seq.map (extractCleanLink &gt;&gt; downloadAndSavePictureAsync)
|&gt; Async.Parallel
|&gt; Async.RunSynchronously
|&gt; ignore</pre>
</div>
<h3>Step 4: cut the profile pictures into layers</h3>
<p>My early experiments with this did not have any feature to cut pictures into layers, but I didn’t want to manually edit each picture profile! So what I’ve done to build “layers” is just to cluster pixels by color similarity (actually I’ve tried to really cluster them with a K-means cluster but I ended up using my custom clustering with magic numbers, as it performs better on that specific set of pictures).</p>
<p>This topic could be a blog post of its own so I’ll just sum up the steps I’ve performed:</p>
<ul>
<li>In order to get rid of outliers, first blur the image
<li>then generate color clusters using the following algorithm:
<ul>
<li>considering each pixel, if it’s close enough (below a given threshold) to an existing cluster, put it in the cluster. If too far from any existing cluster, create a new cluster with the single pixel in it.
<li>after having seen each pixel, merge clusters that are close enough
<li>finally, merge clusters that are too small with their nearest neighbour, regardless of the distance</li>
</ul>
</li>
</ul>
<p>This way, we can go from one image to several ones with the grouped pixels:</p>
<p><img style="float: none; margin: 0px auto; display: block" src="http://www.pirrmann.net/wp-content/uploads/2015/12/Pierre-Irrmann.png" width="200"></p>
<p align="center"><img style="float: none; margin: 0px auto; display: inline" src="http://www.pirrmann.net/wp-content/uploads/2015/12/Pierre-Irrmann-0.png" width="200"><img style="float: none; margin: 0px auto; display: inline" src="http://www.pirrmann.net/wp-content/uploads/2015/12/Pierre-Irrmann-1.png" width="200"><img style="float: none; margin: 0px auto; display: inline" src="http://www.pirrmann.net/wp-content/uploads/2015/12/Pierre-Irrmann-2.png" width="200"></p>
<h3>Step 5: fill images with words</h3>
<p>As some authors have decided to blog more that once, I’ve decided to merge their posts and generate a single image per author.</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let mergePosts posts =
    let allImportantWords =
        posts
        |&gt; Seq.collect (fun post -&gt; post.Words)
        |&gt; Seq.toList
    { Seq.head posts with Words = sumWeights allImportantWords }

let mergedPosts =
    parsePosts allPosts
    |&gt; Seq.groupBy (fun post -&gt; post.Author)
    |&gt; Seq.map(fun (_, posts) -&gt; mergePosts posts)
    |&gt; Seq.toArray</pre>
</div>
<p>Using sumWeights to merge posts is like considering that each post is a paragraph containing only its 100 most important words.</p>
<p>I then consider each layer generated previously from the Twitter profile picture of an author, and fill it with the most important words from his/her posts. This generates one file per layer on the disk.</p>
<h3>Step 6: generate the calendar!</h3>
<p>So… 62 posts (before the last one) – 2 which were not published – 1 because I decided to group Steffen’s posts (even if scheduled on 2 different dates) + 1 because Steffen&#8217;s post have been unmerged (as I neeeded 60 posts in the end) = 60 posts (yeah!). This gives me a nice 8 * 8 square, with a 2 * 2 tile in the middle for the F# foundation! All is needed is to iterate on the generates layers filled with words, and place them on the calendar. I’ve randomly shuffled the posts list, can you identify everybody? Here is the result, enjoy!</p>
<p align="center"><a href="http://www.pirrmann.net/wp-content/uploads/2016/01/calendar.png"><img style="float: none; margin: 0px auto; display: block" src="http://www.pirrmann.net/wp-content/uploads/2016/01/calendar-small.png" width="512">(click on the calendar to view the full size image)</a></p>
<p>I&#8217;ve just updated this post with all posts written so far&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/visualizing-f-advent-calendar-contributors/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Fun with turtles</title>
		<link>http://www.pirrmann.net/fun-with-turtles/</link>
		<comments>http://www.pirrmann.net/fun-with-turtles/#comments</comments>
		<pubDate>Fri, 19 Dec 2014 22:09:42 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[F sharp love]]></category>
		<category><![CDATA[Syntax Puzzles]]></category>
		<category><![CDATA[Computation Expressions]]></category>
		<category><![CDATA[DSL]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[FsAdvent]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=230</guid>
		<description><![CDATA[F# is a great language to build internal DSLs, but I had no idea that you could go as far as what I’m going to present here… Let’s start from the start: my goal was to design some way for &#8230; <a href="http://www.pirrmann.net/fun-with-turtles/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>F# is a great language to build internal DSLs, but I had no idea that you could go as far as what I’m going to present here…</p>
<p>Let’s start from the start: my goal was to design some way for me to explain my daughter what programming is about and how it works. There are some nice graphical tools for that, like <a href="http://scratch.mit.edu/">Scratch</a> or more recently <a href="http://hourofcode.com/">Hour of code</a>, however I wanted to show something which is closer to what I actually do on a daily basis: write (and read) code. There are some nice educational programming languages, some of them are even usable in a localized way (French, in my case). <a href="http://en.wikipedia.org/wiki/Logo_(programming_language)">LOGO</a> is a good example of this, and I could have used an existing tool, but where is the fun if you don’t build your own?</p>
<p>It appears that building an internal LOGO-like DSL is surprisingly easy, and requires almost no code! What you need is just to define the basic types to describe your actions:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">type Distance_Unit = STEPS
type Rotation_Unit = GRADATIONS
type Rotation_Direction = | LEFT | RIGHT
let STEP = STEPS
let GRADATION = GRADATIONS

type Color = | RED | GREEN | BLUE

type Action =
    | Walk of int * Distance_Unit
    | Turn of int * Rotation_Unit * Rotation_Direction
    | LiftPenUp
    | PutPenDown
    | PickColor of Color

type Turtle = Action seq</pre>
</div>
<p>And then a <a href="http://fsharpforfunandprofit.com/series/computation-expressions.html">computation expression</a> to do the trick of transforming sentences to sequences of actions:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">type AS_word = AS
type TO_word = TO
type THE_word = THE
type PEN_word = PEN
type UP_word = UP
type DOWN_word = DOWN
type TIMES_word = TIMES
type WHAT_word = WHAT
type DOES_word = DOES

type TurtleBuilder() =
    member x.Yield(()) = Seq.empty
    [&lt;CustomOperation("WALK", MaintainsVariableSpace = true)&gt;]
    member x.Walk(source:Turtle, nb, unit:Distance_Unit) =
        Seq.append source [Walk(nb, unit)]
    [&lt;CustomOperation("TURN", MaintainsVariableSpace = true)&gt;]
    member x.Turn(source:Turtle, nb, unit:Rotation_Unit, to_word:TO_word,
                  the_word:THE_word, direction:Rotation_Direction) =
        Seq.append source [Turn(nb, unit, direction)]
    [&lt;CustomOperation("LIFT", MaintainsVariableSpace = true)&gt;]
    member x.LiftPenUp(source:Turtle, the_word:THE_word, pen_word:PEN_word,
                       up_word:UP_word) =
        Seq.append source [LiftPenUp]
    [&lt;CustomOperation("PUT", MaintainsVariableSpace = true)&gt;]
    member x.PutPenDown(source:Turtle, the_word:THE_word, pen_word:PEN_word,
                        down_word:DOWN_word) =
        Seq.append source [PutPenDown]
    [&lt;CustomOperation("PICK", MaintainsVariableSpace = true)&gt;]
    member x.PickColor(source:Turtle, the_word:THE_word, color:Color, pen_word:PEN_word) =
        Seq.append source [PickColor color]
    [&lt;CustomOperation("DO", MaintainsVariableSpace = true)&gt;]
    member x.Do(source:Turtle, as_word:AS_word, turtle:Turtle) =
        Seq.append source turtle
    [&lt;CustomOperation("REPEAT", MaintainsVariableSpace = true)&gt;]
    member x.Repeat(source:Turtle, nb:int, times_word:TIMES_word, what_word:WHAT_word,
                    turtle:Turtle, does_word:DOES_word) =
        Seq.append source (List.replicate nb turtle |&gt; Seq.collect id)

let turtle = new TurtleBuilder()</pre>
</div>
<p>And with nothing more, you can now write this kind of plain English instructions:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">turtle {
    LIFT THE PEN UP
    WALK 4 STEPS
    TURN 3 GRADATIONS TO THE RIGHT
    PICK THE GREEN PEN
    PUT THE PEN DOWN
    WALK 4 STEPS }</pre>
</div>
<p>Now, this doesn&#8217;t solve my initial problem, I want a French DSL. But I just need to define another builder, and a few translation functions:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">type Tortue = Turtle

type Unite_De_Distance = PAS with
    member x.enAnglais = match x with | PAS -&gt; STEP

type Unite_De_Rotation = | CRANS with
    member x.enAnglais = match x with | CRANS -&gt; GRADATION
let CRAN = CRANS

type Sens_De_Rotation = | GAUCHE | DROITE with
    member x.enAnglais = match x with
                         | GAUCHE -&gt; LEFT
                         | DROITE -&gt; RIGHT

type Couleur = | ROUGE | VERT | BLEU with
    member x.enAnglais = match x with
                         | ROUGE -&gt; RED
                         | VERT -&gt; GREEN
                         | BLEU -&gt; BLUE

type Mot_A = A
type Mot_DE = DE
type Mot_LE = LE
type Mot_STYLO = STYLO
type Mot_COMME = COMME
type Mot_FOIS = FOIS
type Mot_CE = CE
type Mot_QUE = QUE
type Mot_FAIT = FAIT

type TortueBuilder() =
    member x.Yield(()) = Seq.empty
    member x.For(_) = Seq.empty
    [&lt;CustomOperation("AVANCE", MaintainsVariableSpace = true)&gt;]
    member x.Avance(source:Tortue, de:Mot_DE, nb, unite:Unite_De_Distance) =
        Seq.append source [Walk(nb, unite.enAnglais)]
    [&lt;CustomOperation("TOURNE", MaintainsVariableSpace = true)&gt;]
    member x.Tourne(source:Tortue, de:Mot_DE, nb, unite:Unite_De_Rotation,
                    a:Mot_A, sens:Sens_De_Rotation) =
        Seq.append source [Turn(nb, unite.enAnglais, sens.enAnglais)]
    [&lt;CustomOperation("LEVE", MaintainsVariableSpace = true)&gt;]
    member x.Leve(source:Tortue, le:Mot_LE, stylo:Mot_STYLO) =
        Seq.append source [LiftPenUp]
    [&lt;CustomOperation("POSE", MaintainsVariableSpace = true)&gt;]
    member x.Pose(source:Tortue, le:Mot_LE, stylo:Mot_STYLO) =
        Seq.append source [PutPenDown]
    [&lt;CustomOperation("PRENDS", MaintainsVariableSpace = true)&gt;]
    member x.Prends(source:Tortue, le:Mot_LE, stylo:Mot_STYLO, couleur:Couleur) =
        Seq.append source [PickColor couleur.enAnglais]
    [&lt;CustomOperation("FAIS", MaintainsVariableSpace = true)&gt;]
    member x.Fais(source:Tortue, comme:Mot_COMME, tortue:Tortue) =
        Seq.append source tortue
    [&lt;CustomOperation("REPETE", MaintainsVariableSpace = true)&gt;]
    member x.Repete(source:Tortue, nb:int, fois:Mot_FOIS, ce:Mot_CE, que:Mot_QUE,
                    tortue:Tortue, fait:Mot_FAIT) =
        Seq.append source (List.replicate nb tortue |&gt; Seq.collect id)

let tortue = new TortueBuilder()</pre>
</div>
<p>And I can write my instructions in French!</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">tortue {
    AVANCE DE 5 PAS
    TOURNE DE 6 CRANS A DROITE
    AVANCE DE 5 PAS
    TOURNE DE 6 CRANS A DROITE
    AVANCE DE 5 PAS
    TOURNE DE 6 CRANS A DROITE
    AVANCE DE 10 PAS }</pre>
</div>
<p>The next steps involved:</p>
<ul>
<li>Writing a Windows Forms client to actually see the turtle draw things
<li>Making it possible to send actions to the turtle using FSI
<li>Hand-coding every letter of the alphabet
<li>Adding a new keyword to my turtle builders</li>
</ul>
<p>And please welcome my &#8220;Hello world&#8221; sample:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">turtle {
    WRITE "MR T. SAYS:\nHELLO WORLD!\n\n"
}</pre>
</div>
<p><img src="http://www.pirrmann.net/wp-content/uploads/2014/12/hello-world.gif"> </p>
<p>As usual, all the code is available <a href="https://github.com/pirrmann/Turtles/">on my github</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/fun-with-turtles/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>F# |&gt; I &lt;3</title>
		<link>http://www.pirrmann.net/f-sharp-i-love/</link>
		<comments>http://www.pirrmann.net/f-sharp-i-love/#comments</comments>
		<pubDate>Mon, 07 Apr 2014 06:08:08 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[F sharp love]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Kata]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=226</guid>
		<description><![CDATA[I’ve been writing about F# for a little while now, and how it has influenced the way I code in C# on an everyday basis for 3 years. During the last couple weeks, I’ve finally had the chance to use &#8230; <a href="http://www.pirrmann.net/f-sharp-i-love/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><img style="float: right; margin: 0px 0px 10px 10px; display: inline" src="http://www.pirrmann.net/wp-content/uploads/2014/04/fsharp-pipe-i-love.jpg" width="300" align="right">
<p align="justify">I’ve been writing about F# for a little while now, and how it has influenced the way I code in C# on an everyday basis for 3 years. During the last couple weeks, I’ve finally had the chance to use F# at work for a real project (I’ll probably talk about that later). Yesterday evening (Europe time) at Build, Roslyn was open-sourced. That’s nice and people are probably going to talk about it for a while. But for me there was another very nice announcement : Visual F# is now taking contributions! F# is already an exciting language, full of clever features. With this new step, I’m convinced that it will go even further and I&#8217;m already looking forward to F# 4.0!</p>
<p align="justify">So don’t expect to see many more posts about C# on this blog, I&#8217;ve totally gone F#.</p>
<p align="justify">And now, the latest sample from Arolla’s Code Jam. The aim was to write code to express values with a range of uncertainty, and operations which manipulate those numbers. For instance, a value 3.5 +/- 0.5, multiplied by 1.0 +/- 0.1. The goal of the kata was to write code that expresses intent (the why), and not implementation details (the how).</p>
<p align="justify">In F#, I’ve just defined a type to wrap both the value and its precision, and an operator to conveniently build those values :</p>
<div>
<pre class="brush: fsharp; gutter: false; toolbar: false;">type Number = | Number of float * float

let (+-) n a = Number (n, a)</pre>
</div>
<p align="justify">This code alone already allows me to build values just by writing expressions such as “4.0 +- 1.0”. The next step for me was to write some expressive tests, using FsUnit.</p>
<div>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let [&lt;test&gt;] ``A number with accuracy is equal to itself`` () =
    (1.0 +- 0.5) |&gt; should equal (1.0 +- 0.5)

let [&lt;test&gt;] ``Sum of two numbers sums the numbers and accuracies`` () =
    ((5.0 +- 0.5) + (3.0 +- 0.5)) |&gt; should equal (8.0 +- 1.0)</pre>
</div>
<p>Although we could handle distinctly every operator with specific logic, the goal of this kata is to express the intent in a generic fashion, so here is a combine method that has no specific meaning of what an operator does:</p>
<div>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let combine op (Number(n1, a1), Number(n2, a2)) =
   let all =
      seq {
         for x in [n1-a1; n1+a1] do
         for y in [n2-a2; n2+a2] do
         yield op x y
      }
   let minimum = all |&gt; Seq.min
   let maximum = all |&gt; Seq.max
   Number((minimum + maximum) / 2.0, (maximum - minimum) / 2.0)</pre>
</div>
<p>Finally, we just have to add operator overloading to the type, the full code becomes:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">type Number = | Number of float * float
    with override x.ToString() = match x with | Number(a, b) -&gt; sprintf "%f +- %f" a b
         static member private combine op (Number(n1, a1), Number(n2, a2)) =
            let all =
                seq {
                    for x in [n1-a1; n1+a1] do
                    for y in [n2-a2; n2+a2] do
                    yield op x y
                }
            let minimum = all |&gt; Seq.min
            let maximum = all |&gt; Seq.max
            Number((minimum + maximum) / 2.0, (maximum - minimum) / 2.0)
         static member (+) (x, y) = (x, y) |&gt; Number.combine (+)
         static member (-) (x, y) = (x, y) |&gt; Number.combine (-)
         static member (*) (x, y) = (x, y) |&gt; Number.combine (*)
         static member (/) (x, y) = (x, y) |&gt; Number.combine (/)
         static member Pow (x, y) = (x, y) |&gt; Number.combine ( ** )</pre>
</div>
<p>Thanks to @luketopia for the interactions on Twitter, and the trick which allows to pass the operator ** as an argument: use spaces between the parenthesis and the operator!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/f-sharp-i-love/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pattern matching in C# – part 4 – more tuples</title>
		<link>http://www.pirrmann.net/pattern-matching-in-c-part-4-more-tuples/</link>
		<comments>http://www.pirrmann.net/pattern-matching-in-c-part-4-more-tuples/#comments</comments>
		<pubDate>Sun, 06 Apr 2014 13:29:44 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Functional Inspiration]]></category>
		<category><![CDATA[Syntax Puzzles]]></category>
		<category><![CDATA[AST]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Puzzle]]></category>
		<category><![CDATA[T4]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=222</guid>
		<description><![CDATA[DISCLAIMER: this post has been written months ago and never posted. By that time I was still trying to bring F# goodness to C#. This might be easier today with Roslyn, but that is not the path I’ve taken. Since &#8230; <a href="http://www.pirrmann.net/pattern-matching-in-c-part-4-more-tuples/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>DISCLAIMER: this post has been written months ago and never posted. By that time I was still trying to bring F# goodness to C#. This might be easier today with Roslyn, but that is not the path I’ve taken. Since the last post of this series, I’ve been doing more and more F#, even during my day job. I don’t think I’ll ever post this kind of ‘&#8217;How to do F# in C#” posts. What you can expect from this blog is now mostly functional programming in F#…
<p>Today’s post will be a short one, as an answer to question from several months ago:<br /> 
<p><em>But if we want to handle tuples with more values… do we have to write all the overloads ?!</em></p>
<p><em></em></p>
<p>The answer is yes. With the current implementation, there has to be a method overload for every combination of patterns that you want to be able to match…</p>
<p><em>But wait a minute… For a given tuple of n values, there are 3<sup>n</sup> combinations… That makes a lot of methods to write ?!</em></p>
<p>You don’t have to actually write all these overloads yourself! T4 templates are there exactly for that purpose. If we want to generate all the extensions methods for the tuples of 2 elements up to 4 elements, for instance, we just have to build a .tt file, and define the 3 individual patterns as a string array :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">string[] argumentsPatterns = new[]
{
    "T{0} testValue{0}",
    "Expression&lt;Func&lt;T{0}, bool&gt;&gt; testExpression{0}",
    "MatchCase any{0}"
};</pre>
<p>Then and include a first loop :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">for(int cardinality = 2; cardinality &lt;= 3; cardinality++)
{
    [...]</pre>
<p>As we are going to write the type arguments quite a few times, we store them in a string, as well as the type of the selector argument:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">string typeArguments = string.Join(
    ", ",
    Enumerable.Range(1, cardinality)
              .Select(n =&gt; string.Concat("T", n.ToString())));

string selectorArgument = string.Concat(
    "Expression&lt;Func&lt;",
    typeArguments,
    ", TResult&gt;&gt; selector");</pre>
<p>Inside the first loop we then loop over all the 3<sup>cardinality</sup> combinations :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">for(int caseNumber = 0;
    caseNumber &lt; System.Math.Pow(3, cardinality);
    caseNumber++)
{
    [...]</pre>
<p>And we decompose the caseNumber into an array of int whose values can either be 0, 1 or 2, corresponding to the index of the pattern associated with each argument. For instance, with a cardinality of 4 and a caseNumber or 4, we would get an array containing [0, 0, 1, 1] :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">int[] argumentsPatternsCases = new int[cardinality];
int argumentFlags = caseNumber;
for(int argumentIndex = 0;
    argumentIndex &lt; cardinality;
    argumentIndex++)
{
    argumentsPatternsCases[cardinality - argumentIndex - 1] =
        argumentFlags % 3;

    argumentFlags = argumentFlags / 3;
}</pre>
<p>From all this, we can generate the signature of the method :</p>
<div class="small-code">
<pre class="brush: csharp; gutter: false; toolbar: false;">public static PatternMatcher&lt;Tuple&lt;&lt;#= typeArguments #&gt;&gt;, TResult&gt;
    Case&lt;&lt;#= typeArguments #&gt;, TResult&gt;(
    this PatternMatcher&lt;Tuple&lt;&lt;#= typeArguments #&gt;&gt;, TResult&gt; pattern,
&lt;#
    for(int argumentIndex = 0; argumentIndex &lt; cardinality; argumentIndex++)
    {
#&gt;
    &lt;#= string.Format(argumentsPatterns[argumentsPatternsCases[argumentIndex]], argumentIndex + 1) #&gt;,
&lt;#
    }
#&gt;
    &lt;#= selectorArgument #&gt;)
</pre>
</div>
<p>To understand what happens for the body of the method, the best is to look at the generated code for a particular sample :</p>
<div class="small-code">
<pre class="brush: csharp; gutter: false; toolbar: false;">public static PatternMatcher&lt;Tuple&lt;T1, T2&gt;, TResult&gt; Case&lt;T1, T2, TResult&gt;(
    this PatternMatcher&lt;Tuple&lt;T1, T2&gt;, TResult&gt; pattern,
    Expression&lt;Func&lt;T1, bool&gt;&gt; testExpression1,
    T2 testValue2,
    Expression&lt;Func&lt;T1, T2, TResult&gt;&gt; selector)
{
    ParameterExpression testParam = Expression.Parameter(typeof(Tuple&lt;T1, T2&gt;), "t");
    MemberInfo[] members = GetTupleMembers&lt;T1, T2&gt;();

    List&lt;Expression&gt; testExpressions = new List&lt;Expression&gt;();
    testExpressions.Add(
        Expression.Invoke(
            testExpression1,
            Expression.MakeMemberAccess(testParam, members[0])));
    testExpressions.Add(
        Expression.Equal(
            Expression.MakeMemberAccess(testParam, members[1]),
            Expression.Constant(testValue2)));

    Expression aggregateExpression = testExpressions.CombineAll();

    var testExpression = Expression.Lambda&lt;Func&lt;Tuple&lt;T1, T2&gt;, bool&gt;&gt;(
        aggregateExpression,
        testParam);

    var selectorExpression = GetSelectorExpression&lt;T1, T2, TResult&gt;(selector, members);

    return new PatternMatcher&lt;Tuple&lt;T1, T2&gt;, TResult&gt;(
        pattern,
        new MatchCase&lt;Tuple&lt;T1, T2&gt;, TResult&gt;(
            testExpression,
            selectorExpression));
}</pre>
</div>
<p>I’ve just extracted two methods here :</p>
<ul>
<li>an extension method CombineAll that combines test expressions into a single one by aggregating them using AndAlso expressions :</li>
</ul>
<pre class="brush: csharp; gutter: false; toolbar: false;">private static Expression CombineAll(
    this IEnumerable&lt;Expression&gt; expressions)
{
    Expression aggregateExpression =
        expressions.Aggregate(
            (Expression)null,
            (a, e) =&gt; a == null ? e : Expression.AndAlso(a, e));

    return aggregateExpression ?? Expression.Constant(true);
}</pre>
<ul>
<li>a GetSelectorExpression method, because the selector expression is generated exactly in the same way for each case number of a given cardinality.</li>
</ul>
<p>The whole sample is available <a href="https://github.com/pirrmann/PatternMatching/">on my Github</a>, including hand-crafted unit-tests for tuples of cardinality 2 and 3…</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/pattern-matching-in-c-part-4-more-tuples/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Scala.io, seen by a .NET guy</title>
		<link>http://www.pirrmann.net/scala-io-seen-by-a-net-guy/</link>
		<comments>http://www.pirrmann.net/scala-io-seen-by-a-net-guy/#comments</comments>
		<pubDate>Wed, 30 Oct 2013 05:34:59 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[Functional Inspiration]]></category>
		<category><![CDATA[Clojure]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=220</guid>
		<description><![CDATA[As you might have noticed, I’m a .NET guy. I work on a Microsoft platform, with almost only Microsoft tools. But I happen to also be a functional programming fanboy now. My main interest is in F#, but I’m also &#8230; <a href="http://www.pirrmann.net/scala-io-seen-by-a-net-guy/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p align="justify"><img style="float: right; margin: 0px 0px 10px 10px; display: inline" src="http://www.pirrmann.net/wp-content/uploads/2013/10/scalaio_medium.png" width="300" align="right" height="127">As you might have noticed, I’m a .NET guy. I work on a Microsoft platform, with almost only Microsoft tools. But I happen to also be a functional programming fanboy now. My main interest is in F#, but I’m also curious about many other platforms…</p>
<p align="justify">Last year, I took <a href="https://www.coursera.org/course/progfun">Martin Odersky’s Scala course on coursera</a>, and enjoyed it. I also watched the whole series of <a href="http://channel9.msdn.com/Series/C9-Lectures-Erik-Meijer-Functional-Programming-Fundamentals/">Haskell lectures by Erik Meijer on Channel9</a>. And in a week, for my birthday, both of them offer me a new “<a href="https://www.coursera.org/course/reactive">Reactive programming in Scala</a>” course on coursera!</p>
<p align="justify">With all this background, I went last week to <a href="http://scala.io/">Scala.io</a>, a brand new conference in Paris, mostly about Scala, but also other functional languages. As a not-working-on-the-JVM guy, and not using Scala in my work, I was not focused on tools and practical uses of&nbsp; Scala, but rather on getting ideas from a wide range of practices and languages, and interoperability in mind. As you’ll see, I chose a polyglot track.</p>
<p align="justify">I’ve attended several talks during the two days, but I won’t go into the details of each of these. All the videos should be available soon, so if any of these talks seem interesting to you, watch them!</p>
<h3>Keynote day 1, Victor Klang</h3>
<p align="justify">The opening keynote, given by Victor Klang, head of engineering at Typesafe, focused on the importance of failure, and the need to embrace validation and error handling as part of the software. He envisioned a world of micro-services, concurrent and compartmentalized, location transparent: typed endpoints producing typed streams of data. <em>Of course</em>, he insisted on the importance of type-safety…</p>
<h3>ZeroMQ and Scala, François Armand</h3>
<p align="justify"><a href="http://zeromq.org/">ZeroMQ</a> is a reaction to Message Oriented Middlewares, and the AMQP protocol, which took ages to be specified. ZeroMQ is not a MOM, it is a socket library acting as a concurrency framework. Is is asynchronous and scalable, and has numerous languages integrations. For this reason, it is a convenient communication channel between heterogeneous systems. The talk presented several demos of different communication patterns, using both Scala (with or without Akka) and Python.</p>
<h3>SPL: Scala Powered Lisp, Stefan Chris</h3>
<p align="justify">This talk was about <a href="https://github.com/jaratec/spl">a project to parse and interpret a LISP is Scala</a>. Its goal was to show how parser combinators could be used in Scala to build an AST, and how to build an interpreter and a REPL on top of it.</p>
<p align="justify">After a quick intro about Lisp, and sample expressions evaluated in a REPL, Stefan showed us the definitions of the basic data types of the language, and the Lisp AST he had built. In Scala, all the types were represented as case classes, that can be pattern-matched. After showing the basic constructs, he moved on to anonymous functions, bindings, and more complex expressions. Then came the interpreter, environment and closures.</p>
<h3>Lazy on a Thursday afternoon</h3>
<p align="justify">During the afternoon, I saw some Clojure (I wasn’t that impressed, I should see another more advanced talk some time), reified trees sent to the GPU, JVM Garbage Collection theory and tuning, and then came…</p>
<h3>Brain damage with Haskell, Yves Parès</h3>
<p align="justify">This talk was a general presentation about Haskell, accelerated. It was a very nice talk, first focusing on the non-strict evaluation model of Haskell, where the evaluation is in the hands of the programmer. Yves then showed us several standard functions, and… finally introduced the classical vocabulary of Haskell developers: functors, applicatives, monad. He finally presented several monads usage: IO monad, state monad.</p>
<p align="justify">And after some more Scala patterns, and a nice evening party with the attendees and speakers…</p>
<h3>Keynote day 2, Sadek Drobi</h3>
<p align="justify">This keynote was about web modern challenges, and the motivations behind <a href="http://www.playframework.com/documentation/2.2.x/ScalaTodoList">the Play2 framework</a>. To sum up, Play2 is about composability and functional programming toolset. This really seems to be a pretty nice framework.</p>
<h3>Functional groovy, Guillaume Laforge</h3>
<p align="justify">This was a very nice talk! I had never taken the time to look at <a href="http://groovy.codehaus.org/">Groovy</a>, well this is now solved. Groovy is a superset of Java with APIs and toolset. It is a great fit for DSLs, and offers a seamless integration with Java. It has many functional characteristics: closures are first-class citizens, it supports genericity through duck-typing and operator overloading.</p>
<p align="justify">A very clever feature is the ability to write the last argument of a function, if it is a closure, after the closing parenthesis of the function call. This brings a very nice syntax. Groovy also supports transformations (macros), which allows to automatically add behaviors such a structural equality or memoization to existing code. It’s definitely worth a look.</p>
<h3>Several other talks</h3>
<p align="justify">I attended a talk about Gatling2, a stress test tool that builds a DSL on top of Scala, a talk about Scalaz and Shapeless, Nicolas Martignole talking about his experience working in a startup, and finally Fabrice Croiseaux talking about an app combining Scala, Akka and Backbone for a reactive web application. I have really enjoyed all these talks, but I won’t go into the details of each of these.</p>
<h3>And a conclusion!</h3>
<p>These two days were really nice, there are so many new things I want to learn now… I was already playing with parser combinators in F#, I only want to play with them even more. I am also going to look at structures such as HLists. And of course, <a href="https://www.coursera.org/course/reactive">reactive programming in Scala</a>.</p>
<p align="justify">I really think that it is when we cross boundaries and go outside of our comfort zone that real useful exchanges are made. I had a good time at Scala.io and hope to be there again next year, maybe even doing a talk about F#!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/scala-io-seen-by-a-net-guy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Andy Murray as an event source</title>
		<link>http://www.pirrmann.net/andy-murray-as-an-event-source/</link>
		<comments>http://www.pirrmann.net/andy-murray-as-an-event-source/#comments</comments>
		<pubDate>Tue, 09 Jul 2013 20:21:56 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Kata]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=217</guid>
		<description><![CDATA[With Wimbledon’s final this weekend, I recalled that I had not blogged about the “Evil Tennis kata” I played with, a few months ago. Its aim was to compute a tennis score from a series of game events. This kata &#8230; <a href="http://www.pirrmann.net/andy-murray-as-an-event-source/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><img style="float: right; display: inline" align="right" src="http://www.pirrmann.net/wp-content/uploads/2013/07/mario-tennis.jpg"></p>
<p align="justify">With Wimbledon’s final this weekend, I recalled that I had not blogged about the “Evil Tennis kata” I played with, a few months ago. Its aim was to compute a tennis score from a series of game events. This kata is inspired by the original <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataTennis">tennis kata</a>, but does not stop at the game level and computes the score for a whole match.</p>
<p align="justify">Let’s consider a tennis match. We can see it as a list of points, either won by player A or player B. For instance, here are the first points from Sunday&#8217;s final:</p>
<p>["Murray"; "Murray"; "Murray"; "Djokovic"; "Djokovic"; "Djokovic"; "Djokovic"; "Djokovic"; "Murray"; "Murray"; "Murray"; "Djokovic"; "Murray"; "Djokovic"; "Murray"; "Murray"; "Murray"; "Djokovic"; "Djokovic"; "Djokovic"; "Murray"; "Murray"; "Djokovic"; "Murray"; "Djokovic"; "Murray"; "Murray"; "Djokovic"; "Djokovic"… ]</p>
<p>One of the goals of the kata is to be able to determine the final score from the match events. It can also be to print nicely every score from the start until the end, like it is done for instance on the following page:<br /><a title="http://www.flashscore.com/match/SSmzQE8d/#point-by-point;1" href="http://www.flashscore.com/match/SSmzQE8d/#point-by-point;1">http://www.flashscore.com/match/SSmzQE8d/#point-by-point;1</a></p>
<p>Once again, it has been a nice way to practice F#:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">type Player = PlayerA | PlayerB
type GameEvent = Point of Player
type GameScore = GameScore of int * int
type SetScore = GameScore list
type Match = SetScore list

type Outcome =
    | Win of Player
    | Pending</pre>
</div>
<p align="justify">I use a single union type to define the score of a game, composed of the number of points won by player A and the number of points won by player B. For instance, GameScore(3,1) means that the current game score is 40-15. Using classical integers to count the points is much easier than trying to reason directly in the tennis scoring system, which is seriously twisted. In order to display a classical score from this representation, here is the first function:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let displayGame (GameScore(a, b)) =
    let displayScore score =
        match score with
        | 0 -&gt; "0"
        | 1 -&gt; "15"
        | 2 -&gt; "30"
        | 3 -&gt; "40"
        | _ -&gt; failwith "Invalid argument score"
    match a, b with
    | a, b when a &lt;= 3 &amp;&amp; b &lt;= 3 -&gt; sprintf "%s - %s" (displayScore a) (displayScore b)
    | a, b when a = b -&gt; "Deuce"
    | a, b when a = b + 1 -&gt; "Adv A"
    | a, b when a = b - 1 -&gt; "Adv B"
    | a, b when a &gt; b -&gt; "Game A"
    | _ -&gt; "Game B"</pre>
</div>
<p>Now what we want is to be able to build a GameScore from a series of GameEvent. This can be achieved nicely with a function and a fold:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let updateGame (GameScore(a, b)) event =
    let newGame =
        match event with
        | Point(PlayerA) -&gt; GameScore(a + 1, b)
        | Point(PlayerB) -&gt; GameScore(a, b + 1)
    newGame

[Point(PlayerA);Point(PlayerA);Point(PlayerB);Point(PlayerA)]
|&gt; Seq.fold updateGame (GameScore(0, 0)) 
|&gt; displayGame
</pre>
</div>
<p>The previous sample code prints out the score : “40 &#8211; 15”.</p>
<p>When we try to go a step further, displaying the score of a particular game becomes less interesting. What we really want is to check the victory condition at the game level, in order to determine whether the next point will start a new game:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let getGameOutcome (GameScore(a, b)) =
    match (a, b) with
    | a, b when a &gt; 3 &amp;&amp; a &gt; b + 1 -&gt; Win(PlayerA)
    | a, b when b &gt; 3 &amp;&amp; a &lt; b - 1 -&gt; Win(PlayerB)
    | _ -&gt; Pending</pre>
</div>
<p>From there, we can build an updateSet method:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let updateSet previousSet event =
    match previousSet with
    | previousGame :: previousGames -&gt;
        match getGameOutcome previousGame with
        | Win(_) -&gt; updateGame (GameScore(0, 0)) event :: previousGame :: previousGames
        | Pending -&gt; updateGame previousGame event :: previousGames
    | [] -&gt; updateGame (GameScore(0, 0)) event :: []</pre>
</div>
<p>Similarly, we need to determine at some point whether the set has been won. In order to do this we have to count the games won by each player. Here is how I did it:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let countWins games =
    let rec countWinsRec games (a, b) =
        match games with
        | game :: otherGames -&gt;
            let wins =
                match getGameOutcome game with
                | Win(PlayerA) -&gt; (a + 1, b)
                | Win(PlayerB) -&gt; (a, b + 1)
                | _ -&gt; (a, b)
            countWinsRec otherGames wins
        | _ -&gt; (a, b)
    countWinsRec games (0, 0)</pre>
</div>
<p>From there, we can determine whether a set is won:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let getSetOutcome (setScore:SetScore) =
    let (a, b) = countWins setScore
    match (a, b) with
    | a, b when a &gt; 5 &amp;&amp; a &gt; b + 1 -&gt; Win(PlayerA)
    | a, b when b &gt; 5 &amp;&amp; a &lt; b - 1 -&gt; Win(PlayerB)
    | _ -&gt; Pending</pre>
</div>
<p>The next step is to move to the match level:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let updateMatch previousMatch event =
    match previousMatch with
    | previousSet :: previousSets -&gt;
        match getSetOutcome previousSet with
        | Win(_) -&gt; updateSet [] event :: previousSet :: previousSets
        | Pending -&gt; updateSet previousSet event :: previousSets
    | [] -&gt; updateSet [] event :: []</pre>
</div>
<p>Finally, we can use the updateMatch method in a fold to build a representation of the match:</p>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let buildMatch events = List.fold updateMatch [] events</pre>
<p>The result is a reversed list of reversed list of GameScores…</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">[[GameScore (6,8); GameScore (1,4); GameScore (2,4); GameScore (2,4);
  GameScore (4,1); GameScore (4,1); GameScore (4,2); GameScore (4,2);
  GameScore (0,4); GameScore (2,4)];
 [GameScore (0,4); GameScore (2,4); GameScore (2,4); GameScore (4,0);
  GameScore (5,7); GameScore (4,6); GameScore (1,4); GameScore (4,2);
  GameScore (4,1); GameScore (4,2); GameScore (3,5); GameScore (4,1)];
 [GameScore (0,4); GameScore (5,3); GameScore (5,7); GameScore (0,4);
  GameScore (0,4); GameScore (4,2); GameScore (4,1); GameScore (6,8);
  GameScore (1,4); GameScore (5,3)]]
</pre>
</div>
<p>That is not a very readable result… Here I go for a last function:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let displayMatchScore events = 
    let displaysWins (a, b) = sprintf "%i - %i" a b
    let displaySet games = displaysWins (countWins games)
    let rec getSetScoreToDisplay sets =
        match sets with
        | games :: [] -&gt;
            match games with
            | game :: _ -&gt; displaySet games :: []
            | _ -&gt; displaySet games :: []
        | games :: otherSets -&gt; displaySet games :: getSetScoreToDisplay otherSets
        | [] -&gt; failwith "Error"
    getSetScoreToDisplay (buildMatch events |&gt; List.rev)</pre>
</div>
<p>This last one aggregates the events, in order to display a much more simple list of scores:</p>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let score = displayMatchScore events</pre>
<p>And the final score is displayed : <strong>["4 - 6"; "5 - 7"; "4 - 6"] !</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/andy-murray-as-an-event-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Potter Kata – Going further – Not following the rule</title>
		<link>http://www.pirrmann.net/potter-kata-going-further-not-following-the-rule/</link>
		<comments>http://www.pirrmann.net/potter-kata-going-further-not-following-the-rule/#comments</comments>
		<pubDate>Sun, 07 Jul 2013 19:45:21 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Kata]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=213</guid>
		<description><![CDATA[Last time, I blogged about the Potter Kata, and I carefully followed the advice, which was to only do the minimum required work to pass the tests. This time, I’m going to break the rule and implement a generic solver &#8230; <a href="http://www.pirrmann.net/potter-kata-going-further-not-following-the-rule/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p align="justify">Last time, <a href="http://www.pirrmann.net/potter-kata/">I blogged about the Potter Kata</a>, and I carefully followed the advice, which was to only do the minimum required work to pass the tests. This time, I’m going to break the rule and implement a generic solver for the problem, although it may have no practical interest whatsoever.
<p align="justify">Let’s pretend that in the pricing rules applied last time, the discount percentages could change, depending on the mood of a very lunatic sales person. For instance, he (or she) might decide that on a particular day, we remove the discount on the pack of two books, and introduce a “buy 2, get 1 free” offer. The prices would then become:</p>
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td>1 book</td>
<td>No discount</td>
<td align="right">8.00 EUR</td>
</tr>
<tr>
<td>2 different books</td>
<td><strong>No discount</strong></td>
<td align="right">8.00 * 2 = 16.00 EUR</td>
</tr>
<tr>
<td>3 different books</td>
<td><strong>3rd one free</strong></td>
<td align="right">8.00 * 2 + 0.00 * 1 = 16.00 EUR</td>
</tr>
<tr>
<td>4 different books</td>
<td>20% discount</td>
<td align="right">8.00 * 4 *0.80 = 25.60 EUR</td>
</tr>
<tr>
<td>5 different books</td>
<td>25% discount</td>
<td align="right">8.00 * 5 *0.75 = 30.00 EUR</td>
</tr>
</tbody>
</table>
<p>Now, let’s examine the previous “edge-case” basket, composed of:</p>
<ul>
<li>2 copies of the first book
<li>2 copies of the second book
<li>2 copies of the third book
<li>1 copy of the fourth book
<li>1 copy of the fifth book</li>
</ul>
<p align="justify">With the new pricing rules, the new best price is obtained by (5 * 8.0 * 0.75) + (2 * 8.00 + 1 * 0.00) and is 46.00 EUR. Here, the greedy algorithm is correct again, so we could just remove our adjustment rule from last time, isn’t it? Of course not! If we add one more book in the basket, the best price becomes… 3 * (2 * 8.00 + 1 * 0.00) = 48.00 EUR.</p>
<p align="justify">So how do we solve that ? Well, we could simply try a brute force solution, compute every single possible set of sets of books, price them, and take the cheapest option. But here we have an interesting property: every book has the same price. So evaluating [[1;2];[1;2];[3]] and [[1;2];[1;3];[2]] is exactly the same. When we consider books, we don’t really care about their individual number or title, but only about whether they are distinct from each other or not.</p>
<p align="justify">So here is my take on a solver algorithm. First, we take the books and organize them by types, sorted by ascending quantity:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let types = books |&gt; Seq.countBy id |&gt; Seq.map snd |&gt; Seq.sort |&gt; Seq.toList |&gt; List.rev</pre>
</div>
<p align="justify">This means that the following books [1;2;3;1;2;3;4;5] get transformed to the list [1;1;2;2;2], which means “a book that appears only once, then another one, then one that appears twice, then another one, and yet another one”.</p>
<p align="justify">From this representation, we can price the basket by splitting it into two simpler baskets, in several ways, price each combinations, and take the cheapest. To split the basket, we remove a single item of each kind of book, for the first <em>n</em> types. An example is worth a thousand words here:</p>
<p>From [1;1;2;2;2] we can get the following splittings:</p>
<ul>
<li>[1] + [1;2;2;2]
<li>[1;1] + [2;2;2]
<li>[1;1;1] + [1;2;2]
<li>[1;1;1;1] + [1;1;2]
<li>[1;1;1;1,1] + [1;1;1]</li>
</ul>
<p align="justify">The first half is always priced directly as there is never more than one book of each kind. The second half is priced recursively using the same principle.</p>
<p align="justify">The algorithm is the following:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let rec priceTypes priceBucket (types: int list) =
    let nbTypes = List.length types
    if nbTypes = 0 then 0.0M
    else
        let allPrices = seq {
            for bucketSize = 1 to nbTypes do
                let bucketPrice = priceBucket bucketSize
                let remainingTypes =
                    types
                    |&gt; Seq.mapi (fun i n -&gt; if i &lt; bucketSize then n - 1 else n)
                    |&gt; Seq.filter (fun n -&gt; n &gt; 0)
                    |&gt; Seq.sort |&gt; Seq.toList |&gt; List.rev

                yield bucketPrice + priceTypes priceBucket remainingTypes }
        allPrices |&gt; Seq.min</pre>
</div>
<p align="justify">There are <strong>many</strong> combinations. This will lead to <strong>long</strong> computations, even with a low number of books. But many of these computations will share some identical combinations, and they don’t need to be run several times. This is just what memoization is designed for. The principle is simple: when an idempotent function gets the same input twice, it must generate the same output. From there, if we can record the generated output the first time and associate it with the input, the next time we get this input we can directly return the recorded output.</p>
<p>A standard memoize function can then be defined:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let memoize f =
    let dict = Dictionary&lt;_, _&gt;()
    fun x -&gt;
        match dict.TryGetValue(x) with
        | true, res -&gt; res
        | false, _ -&gt; 
            let res = f x
            dict.Add(x, res)
            res</pre>
</div>
<p>The things get a little more complicated when recursion is involved because in order to memoize effectively a recursive function, the function itself has to call its memoized version recursively (instead of itself). It gets even more complicated if you need the whole recursive thing to be tail-recursive. For now, hopefully, we don’t need that, because the tree of combinations that we try to build is quite wide, but not very deep.</p>
<p>My implementation of the memoized version is the following:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let rec priceTypes priceBucketFunc =
    let rec memoizedPriceTypes =
        let priceTypesRaw (types: int list) =
            let nbTypes = List.length types
            if nbTypes = 0 then 0.0M
            else
                let allPrices = seq {
                    for bucketSize = 1 to nbTypes do
                        let bucketPrice = priceBucketFunc bucketSize
                        let remainingTypes =
                            types
                            |&gt; Seq.mapi (fun i n -&gt; if i &lt; bucketSize then n - 1 else n)
                            |&gt; Seq.filter (fun n -&gt; n &gt; 0)
                            |&gt; Seq.sort |&gt; Seq.toList |&gt; List.rev

                        yield bucketPrice + memoizedPriceTypes remainingTypes }
                allPrices |&gt; Seq.min
        memoize priceTypesRaw
    memoizedPriceTypes</pre>
</div>
<p>We can now build a price function that takes a “priceBucket” function as an argument, and returns the actual pricing function:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let price priceBucketFunc books =
    let types = books |&gt; Seq.countBy id |&gt; Seq.map snd |&gt; Seq.sort |&gt; Seq.toList |&gt; List.rev
    priceTypes priceBucketFunc types</pre>
</div>
<p>The function can then be used this way:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let priceBucket = function | 1 -&gt; 8.0M | 2 -&gt; 16.0M | 3 -&gt; 16.0M | 4 -&gt; 25.6M
                           | 5 -&gt; 30.0M | _ -&gt; failwith "Really ? 6 books ?"
let price = PotterKataTooMuch.price priceBucket
price [1;1;2;2;3;3;4;5]</pre>
</div>
<p>It works on small to medium lists of books (such as 50 books for instances). Let’s pretend the world is perfect, and that it’s enough for today!</p>
<p>The code from this post and the previous one is <a href="https://github.com/pirrmann/PotterKata/">available on GitHub</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/potter-kata-going-further-not-following-the-rule/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Potter Kata</title>
		<link>http://www.pirrmann.net/potter-kata/</link>
		<comments>http://www.pirrmann.net/potter-kata/#comments</comments>
		<pubDate>Fri, 05 Jul 2013 05:13:09 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Kata]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=211</guid>
		<description><![CDATA[Yesterday evening I was running Arolla’s Code Jam, and I suggested that we practice on the Potter Kata. This kata is a tricky one, which seems pretty simple at first, but shows its challenges after a few minutes, and it &#8230; <a href="http://www.pirrmann.net/potter-kata/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p align="justify"><img style="float: right; margin: 0px 0px 10px 10px; display: inline" align="right" src="http://www.pirrmann.net/wp-content/uploads/2013/07/2013-07-Jam-Potter-Kata.jpg">
<p align="justify">Yesterday evening I was running <a href="http://www.arolla.fr/evenements-2/jams-de-code/">Arolla’s Code Jam</a>, and I suggested that we practice on the <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataPotter">Potter Kata</a>. This kata is a tricky one, which seems pretty simple at first, but shows its challenges after a few minutes, and it is very easy to get it wrong. In order to prepare the Jam and improve my level in F#, I practiced the kata this week, and I wanted to share my thoughts about it.
<p align="justify">You can <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataPotter">read the original problem description on codingdojo.org</a>. I’ll just recap the pricing rules here for reference:</p>
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td>1 book</td>
<td>No discount</td>
<td align="right">8.00 EUR</td>
</tr>
<tr>
<td>2 different books</td>
<td>5% discount</td>
<td align="right">8.00 * 2 *0.95 = 15.20 EUR</td>
</tr>
<tr>
<td>3 different books</td>
<td>10% discount</td>
<td align="right">8.00 * 3 *0.90 = 21.60 EUR</td>
</tr>
<tr>
<td>4 different books</td>
<td>20% discount</td>
<td align="right">8.00 * 4 *0.80 = 25.60 EUR</td>
</tr>
<tr>
<td>5 different books</td>
<td>25% discount</td>
<td align="right">8.00 * 5 *0.75 = 30.00 EUR</td>
</tr>
</tbody>
</table>
<p>The rules are then followed by some clues:<br />
<blockquote>
<p>You’ll find that this Kata is easy at the start. You can get going with tests for baskets of 0 books, 1 book, 2 identical books, 2 different books… and it is not too difficult to work in small steps and gradually introduce complexity.
<p>However, the twist becomes apparent when you sit down and work out how much you think the sample basket above should cost. It isn’t 5*8*0.75+3*8*0.90. It is in fact 4*8*0.8+4*8*0.8. So the trick with this Kata is not that the acceptance test you’ve been given is wrong. The trick is that you have to write some code that is intelligent enough to notice that two sets of four books is cheaper than a set of five and a set of three.
<p>You will have to introduce a certain amount of clever optimization algorithm. But not too much! This problem does not require a fully-fledged general purpose optimizer. Try to solve just this problem well in order to share it. Trust that you can generalize and improve your solution if and when new requirements come along.</p>
</blockquote>
<p align="justify">It is clear here that the goal of this kata is not to write a general-purpose solver. I must agree that a general-purpose solver is not the best solution to the problem, as most probably <a href="http://en.wikipedia.org/wiki/YAGNI">You Aren’t Gonna Need It</a>.
<p align="justify">So I first tackled the kata, trying to do the bare minimum required to handle the requirements. In F#, my implementation goes down to 20 lines of code. The trick is that a greedy grouping of books (the “most intuitive” solution) is correct, except for the corner case where a group of 5 five books and a group of 3 books is actually more expensive than t<a name="_GoBack"></a>wo groups of 4 books.
<p align="justify"><strong>Disclaimer:</strong> I’m going to show an implementation of the kata here. If you’ve never tried it before, I suggest that you practice on your own first, because the solution in itself is really not as valuable as the path to get there.
<p align="justify">I’ll use some of the test cases provided in the original kata, plus the ones we came up with last night. In F#, I get these kinds of tests:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">[&lt;TestMethod&gt;]
member x.``1 book (each kind)`` () = 
    Assert.AreEqual(8.0M, price [1])
    Assert.AreEqual(8.0M, price [2])
    Assert.AreEqual(8.0M, price [3])
    Assert.AreEqual(8.0M, price [4])
    Assert.AreEqual(8.0M, price [5])

[&lt;TestMethod&gt;]
member x.``2 same books`` () = 
    Assert.AreEqual(16.0M, price [1;1])
    Assert.AreEqual(24.0M, price [2;2;2])

[&lt;TestMethod&gt;]
member x.``2 distinct books`` () = 
    Assert.AreEqual(15.2M, price [1;2])

[&lt;TestMethod&gt;]
member x.``3 distinct books`` () = 
    Assert.AreEqual(21.6M, price [1;2;3])

[&lt;TestMethod&gt;]
member x.``4 distinct books`` () = 
    Assert.AreEqual(25.6M, price [1;2;3;4])

[&lt;TestMethod&gt;]
member x.``5 distinct books`` () = 
    Assert.AreEqual(30.0M, price [1;2;3;4;5])

[&lt;TestMethod&gt;]
member x.``Simple discount`` () = 
    Assert.AreEqual(29.6M, price [1;2;1;3])</pre>
</div>
<p align="justify">If we read the test cases carefully, nothing forces us to have a notion of “discount” in our implementation. In fact, pricing a group of distinct books is almost a single-liner:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let priceGroup = function | 1 -&gt; 8.0M | 2 -&gt; 15.2M | 3 -&gt; 21.6M
                          | 4 -&gt; 25.6M | 5 -&gt; 30.0M | _ -&gt; failwith "What ? A 6th book ?"</pre>
</div>
<p align="justify">Now, this obviously doesn’t work when we try to buy the same book more than once. In order to consume the previously defined function, we have to build groups of books. A greedy grouping seems accurate at first: </p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let greedyGroup books = 
    // we count how many books there are of each type and sort them
    let types = books |&gt; Seq.countBy id |&gt; Seq.map snd |&gt; Seq.sort |&gt; Seq.toList
    // then we recursively compute how many groups of books we can build
    let rec countGroups types used =
        match types with
        | [] -&gt; []
        | head :: tail -&gt; head - used :: countGroups tail head
    countGroups types 0 |&gt; List.rev</pre>
</div>
<p align="justify">I’m pretty happy with function. The first expression get en ordered list from the books: a list of books [1;1;2;2;3;4] produces a list of of types of books [1;1;2;2], that can be read as “a type with a single book, a type with a single book, a type with 2 books, a type with 2 books”. The recursive function counts how many groups of distinct books can be built from these type. Here, the output is [0;1;0;1] which means “0 group of 1 books, 1 group of 2 books, 0 group of 3 books, 1 group of 4 books”. </p>
<p align="justify">Now, we combine our functions into a price function: </p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let price books =
    books
    |&gt; greedyGroup
    |&gt; Seq.mapi (fun i nb -&gt; priceGroup (i+1) * decimal nb)
    |&gt; Seq.sum</pre>
</div>
<p align="justify">We’re almost there. This code is incorrect for the edge case we identified before. But do we have to break everything and build a general-purpose solver? No. We just have to handle the edge case and adjust the grouping: </p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let adjust = function 
    | [a; b; c; d; e] -&gt;
        let shift = min c e
        [a; b; c-shift; d+2*shift; e-shift]
    | l -&gt; l</pre>
</div>
<p>Basically, this adjust function replaces every pair of 5 distinct books and 3 distinct books by a 2 groups of 4 distinct books, which are cheaper.</p>
<p>Finally, the pricing function with the adjustment becomes:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let price books =
    books
    |&gt; greedyGroup
    |&gt; adjust
    |&gt; Seq.mapi (fun i nb -&gt; priceGroup (i+1) * decimal nb)
    |&gt; Seq.sum</pre>
</div>
<p align="justify">And that’s done. </p>
<p align="justify"><em>Bonus:</em> F# brings you such a nice type inference that without changing any line in my previous code, I can use the book titles instead of their numbers (or anything that has equality comparison!). </p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let test_generic_1 = price ["Harry Potter and the Philosopher's Stone";
                            "Harry Potter and the Chamber of Secrets";
                            "Harry Potter and the Prisoner of Azkaban";
                            "Harry goes to Hollywood";
                            "Harry Rabienkirira - ledernier"]

let test_generic_2 = price [typedefof&lt;System.Collections.ArrayList&gt;;
                            typedefof&lt;System.String&gt;;
                            typedefof&lt;System.Int32&gt;]</pre>
</div>
<p align="justify">Of course, building a general purpose solver for the same problem is too appealing to be ignored. <strong>That will be the subject of the next post</strong>, featuring tail-recursion and memoization! </p>
<p align="justify"><em>(For those of you who wonder where the “Pattern-matching” series has gone, it’s coming back soon)</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/potter-kata/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Alt.net Coding Breakfast – June 2013 Edition</title>
		<link>http://www.pirrmann.net/alt-net-coding-breakfast-june-2013-edition/</link>
		<comments>http://www.pirrmann.net/alt-net-coding-breakfast-june-2013-edition/#comments</comments>
		<pubDate>Tue, 18 Jun 2013 03:59:14 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[Alt.Net]]></category>
		<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=208</guid>
		<description><![CDATA[Two weeks ago on Wednesday morning, I went to the latest edition of Alt.Net Coding Breakfast, hosted by Damien Thouvenin of CLT Services. It was my first time there, and I was very pleased with it. The principle is quite &#8230; <a href="http://www.pirrmann.net/alt-net-coding-breakfast-june-2013-edition/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p align="justify">Two weeks ago on Wednesday morning, I went to the latest edition of Alt.Net <a href="http://www.meetup.com/altnetfr/events/116746562/">Coding Breakfast</a>, hosted by <a href="http://www.blogdepatron.fr/">Damien Thouvenin</a> of CLT Services. It was my first time there, and I was very pleased with it. The principle is quite simple: several .Net coders meet in the morning, and practice their skills by attempting a Coding Kata during an hour. We then review together what was done, what went well and what went wrong. It is an exercise that I find very useful (and fun), that I usually do during <a href="http://www.arolla.fr/evenements-2/jams-de-code/">Arolla’s Code Jam</a> on Thursdays. This coding breakfast’s main advantage is to meet with other .Net practitioners (as usually the Java guys are predominant) and that might be the only place in Paris where you can see <strong>several people coding in F#</strong>. That was also true last month, as you can see on <a href="http://strangelights.com/blog/archive/2013/04/27/alt-net-coding-breakfast-ndash-april-2013-edition.aspx">Robert Pickering’s blog</a>.</p>
<p>This month, the kata was about printing user-supplied pictures:</p>
<ul>
<li>of any size (in pixels),
<li>in a given format (10&#215;13 cm, 11&#215;13 cm, 13x15cm, 15&#215;18 cm, 18&#215;24 cm…)
<li>with a given filling mode (“full-paper” or “full-image”)</li>
</ul>
<p align="justify">The printer always prints at 300 dots-per-inch, so the images must be resized in order to fit in the available printing space.</p>
<p>The expected output data, needed for printing the images, would be:</p>
<ul>
<li>the output printer (13 cm width or 18 cm width printer),
<li>the rotation applied to the picture (0° or 90°, the direction doesn’t matter),
<li>the expansion/reduction ratio to apply to the picture,
<li>the position where the picture must be drawn.</li>
</ul>
<p align="justify">The kata’s description also involved some drawings in order to explain the meaning of the filling modes. There was, for instance, a picture of Winston Churchill. Unfortunately, there was not a single kitten picture. I fixed this, in order to provide samples illustrating the two filling modes.</p>
<p>Here is a train picture in full-image mode:</p>
<p><img style="border-top: black 1px solid; border-right: black 1px solid; border-bottom: black 1px solid; float: none; margin-left: auto; border-left: black 1px solid; display: block; margin-right: auto" src="http://www.pirrmann.net/wp-content/uploads/2013/06/train-18-24-full-image.png"></p>
<p>The same picture in full-paper mode, where the red areas will be cropped at printing:</p>
<p><img style="border-top: black 1px solid; border-right: black 1px solid; border-bottom: black 1px solid; float: none; margin-left: auto; border-left: black 1px solid; display: block; margin-right: auto" src="http://www.pirrmann.net/wp-content/uploads/2013/06/train-18-24-full-paper.png"></p>
<p>And the same with the kitten, full-image:</p>
<p><img style="border-top: black 1px solid; border-right: black 1px solid; border-bottom: black 1px solid; float: none; margin-left: auto; border-left: black 1px solid; display: block; margin-right: auto" src="http://www.pirrmann.net/wp-content/uploads/2013/06/kitten-18-24-full-image.png"></p>
<p>And full-paper, with the cropped areas in red:</p>
<p><img style="border-top: black 1px solid; border-right: black 1px solid; border-bottom: black 1px solid; float: none; margin-left: auto; border-left: black 1px solid; display: block; margin-right: auto" src="http://www.pirrmann.net/wp-content/uploads/2013/06/kitten-18-24-full-paper.png"></p>
<p align="justify">The exercise chosen by Damien for this kata is really an interesting one, as it is in fact quite simple, but there are many ways to misunderstand it and make it more complicated than it really is. Although we were not so many coders, there were several different techniques, problems and outcomes:</p>
<ul>
<li>
<div align="justify">some people paired, some worked alone, </div>
<li>
<div align="justify">some worked in TDD, some didn’t (but we all wrote tests!), </div>
<li>
<div align="justify">some of us didn’t consider the print format as an input but rather as an output (trying to determine the most appropriate format for a given picture), </div>
<li>
<div align="justify">some of us took much time trying to define data types, and in the end had not enough time to handle the core business problem of the image resizing, </div>
<li>
<div align="justify">some others (amongst the C# devs) used dynamic types for prototyping, so they were able to write the logic first, rather than focusing on the types.</div>
</li>
</ul>
<p align="justify">As to myself, I had come to this breakfast with the goal to code in F#, so this is what I’ve done. I paired with Peter Even, who I hope is now addicted to F#! In order to focus on the core problem, we stated that:</p>
<ul>
<li>selecting the good output printer given the print format is trivial,
<li>selecting whether or not we must rotate is not very complicated (although we could get it wrong),
<li>the ratio computation is the tricky part.</li>
</ul>
<p align="justify">Here is what we came up with (with the French words translated) for the ratio computation. First the unit tests:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">[&lt;TestClass&gt;]
type UnitTest() = 
    [&lt;TestMethod&gt;]
    member x.``A 2.54*2.54cm square is 300*300 pixels`` () = 
        let converted = (2.54, 2.54) |&gt; toPixels
        Assert.AreEqual((300.0, 300.0), converted)
        
    [&lt;TestMethod&gt;]
    member x.``Winston churchill in 18*24cm full-image`` () = 
        let ratio = getResizeRatio (664, 1000) (18.0, 24.0) FullImage
        Assert.AreEqual(18.0 * 300.0 / 2.54 / 664.0, ratio)

    [&lt;TestMethod&gt;]
    member x.``Winston churchill in 18*24cm full-paper`` () = 
        let ratio = getResizeRatio (664, 1000) (18.0, 24.0) FullPaper
        Assert.AreEqual(24.0 * 300.0 / 2.54 / 1000.0, ratio)</pre>
</div>
<p>And here is the implementation:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">type Mode =
    | FullImage
    | FullPaper

let toPixels (x, y) =
    (x * 300.0 / 2.54, y * 300.0 / 2.54)

let getResizeRatio (photoHeight, photoWidth) (formatHeight, formatWidth) mode  =
    let (photoHeight, photoWidth) = (float photoHeight, float photoWidth)
    let (paperWidth, paperHeight) = toPixels (formatWidth, formatHeight)

    let photoRatio = photoWidth / photoHeight
    let formatRatio = formatWidth / formatHeight

    let isPhotoWider = photoRatio &gt; formatRatio

    match (isPhotoWider, mode) with
    | (true, FullImage) | (false, FullPaper) -&gt; paperWidth / photoWidth
    | (false, FullImage) | (true, FullPaper) -&gt; paperHeight / photoHeight</pre>
</div>
<p align="justify"><a href="http://thinkbeforecoding.com/">Jérémie Chassaing</a>, who also worked in F#, had a more engineered solution where he:</p>
<ul>
<li>
<div align="justify">determines, from the filling-mode, which operator to use in order to compare the ratios, </div>
<li>
<div align="justify">performs the comparison with the operator and determines from that which side of the image must be used to get the correct ratio (but the return type here is directly a function, where a less-functional approach would have returned a boolean for instance), </div>
<li>
<div align="justify">uses the resulting function to extract the length and compute the ratio.</div>
</li>
</ul>
<p align="justify">It sounds more complicated (to my mind it is, in fact), but I still find that beautiful from a functional perspective!</p>
<p align="justify">While writing this blog post, I could not resist the will to go further and investigate the other parts of the problem, because I so much wanted to be able to pipe my functions! In the end, the assumptions we made during the kata were not wrong, but reasoning about the position where the image must be drawn is not as simple as I first thought!</p>
<p>Finally, here is my code:</p>
<div class="small-code">
<pre class="brush: fsharp; gutter: false; toolbar: false;">let printers = [ 13.0; 18.0 ]

let findPrinter (formatShortSide, formatLongSide) =
    let printerWidth = printers |&gt; List.tryFind (fun w -&gt; w = formatShortSide || w = formatLongSide)
    Option.bind (fun w -&gt; Some(w, w = formatShortSide)) printerWidth

let getResizeRatio (photoShortSide, photoLongSide) (frameShortSide, frameLongSide) mode  =
    let isPhotoRatioHigher = (photoLongSide / photoShortSide) &gt; (frameLongSide / frameShortSide)
    match (isPhotoRatioHigher, mode) with
    | (true, FullImage) | (false, FullPaper) -&gt; frameLongSide / photoLongSide
    | (false, FullImage) | (true, FullPaper) -&gt; frameShortSide / photoShortSide

let getPrintData (photoWidth, photoHeight) (formatShortSide, formatLongSide) mode =
    let printer = findPrinter (formatShortSide, formatLongSide)
    match printer with
    | Some(printerWidth, withFormatRotation) -&gt;
        let (withPhotoRotationInFrame, photoShortSide, photoLongSide) =
            if photoHeight &gt; photoWidth
                then (true, float photoWidth, float photoHeight)
                else (false, float photoHeight, float photoWidth)
        
        let (frameLongSide, frameShortSide) = (formatLongSide, formatShortSide) |&gt; toPixels

        let ratio = getResizeRatio (photoShortSide, photoLongSide) (frameShortSide, frameLongSide) mode

        let xInFrame = (frameLongSide - photoLongSide * ratio) / 2.0
        let yInFrame = (frameShortSide - photoShortSide * ratio) / 2.0

        let (x, y) = if withFormatRotation
                        then (yInFrame, xInFrame)
                        else (xInFrame, yInFrame)

        let withRotation = withFormatRotation &lt;&gt; withPhotoRotationInFrame

        Some(printerWidth, (x, y) |&gt; toCentimeters, withRotation)

    | None -&gt; None</pre>
</div>
<p><font size="1">Notes: the images used in the samples are under a creative commons license, and can be found at </font><a href="http://commons.wikimedia.org/wiki/File:Antigo_Tren_Old_Train._Santiago_de_Compostela.jpg"><font size="1">http://commons.wikimedia.org/wiki/File:Antigo_Tren_Old_Train._Santiago_de_Compostela.jpg</font></a><font size="1"> and&nbsp; </font><a href="http://commons.wikimedia.org/wiki/File:Red_Kitten_01.jpg"><font size="1">http://commons.wikimedia.org/wiki/File:Red_Kitten_01.jpg</font></a><font size="1">.</font></p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/alt-net-coding-breakfast-june-2013-edition/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Pattern matching in C# – part 3 – tuples</title>
		<link>http://www.pirrmann.net/pattern-matching-in-c-part-3-tuples/</link>
		<comments>http://www.pirrmann.net/pattern-matching-in-c-part-3-tuples/#comments</comments>
		<pubDate>Wed, 20 Mar 2013 20:58:19 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Functional Inspiration]]></category>
		<category><![CDATA[Syntax Puzzles]]></category>
		<category><![CDATA[AST]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Puzzle]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=201</guid>
		<description><![CDATA[Hello again, you potential RSS subscriber (probably still reading this in Google Reader, trying to determine which reader you’ll choose next) ! Last time I left you with a working pattern-matching mechanism in C#, but very limited… as it could &#8230; <a href="http://www.pirrmann.net/pattern-matching-in-c-part-3-tuples/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Hello again, you potential RSS subscriber (probably still reading this in Google Reader, trying to determine which reader you’ll choose next) ! Last time I left you with a working pattern-matching mechanism in C#, but very limited… as it could only match a single value at a time.</p>
<p>What makes the pattern-matching mechanism so powerful in functional languages is its ability to match many sorts of data structures, amongst which are tuples.</p>
<p>Defining a match expression on a tuple or 2 values in F# can be done this way :</p>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let result =
    match input with
    | 1, 1 -&gt; 1
    | 2, _ -&gt; 2
    | _, 3 -&gt; 3
    | a, b when a &gt; 4 -&gt; 4
    | _ -&gt; 5</pre>
<p>This sample shows some interesting cases. A tuple of 2 values can be matched with several expressions, each value of the tuple being compared with individual patterns.</p>
<p>In part 1 of this series, we stated these individual patterns:</p>
<ul>
<li>a constant pattern,
<li>a conditional pattern,
<li>a default pattern, known as the wildcard pattern (the underscore in F#).</li>
</ul>
<p>Now, we have to handle every possible combination of these patterns!</p>
<p>The following sample translated in C# in my experimental syntax is the following:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var tupleSample =
    PatternMatcher.CreateSwitch&lt;int, int, int&gt;()
    .Case(1         , 1, (a, b) =&gt; 1)
    .Case(2         , _, (a, b) =&gt; 2)
    .Case(_         , 3, (a, b) =&gt; 3)
    .Case(a =&gt; a &gt; 4, _, (a, b) =&gt; 4)
    .Case(_         , _, (a, b) =&gt; 5);</pre>
<p>Welcome to the parenthesis hell. Soon it will like like Lisp if we go on… But how do we enable that syntax ?</p>
<p>In order to handle gracefully the wildcard (“_”) pattern, I have used a non-generic <em>MatchCase</em> class with a static field called Any:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class MatchCase
{
    public static readonly MatchCase Any;

    static MatchCase()
    {
        Any = new MatchCase();
    }

    private MatchCase()
    {
    }
}</pre>
<p>This trick allows me to define methods with a <em>MatchCase</em>-typed parameter to handle the wildcard pattern case. Moreover, if I add the following line before my patterns definitions :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var _ = MatchCase.Any;</pre>
<p>I’m then able to use a simple “_” to represent the “any” case.</p>
<p>The method used previously to build the pattern matching Func and its invocation in the Eval method doesn’t change: only the “recording” process is impacted. The pain point here is that we need to define each necessary overload of the <em>Case</em> extension method, in order to handle all the patterns. These extensions methods are all based on the following model:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public static PatternMatcher&lt;Tuple&lt;T1, T2&gt;, TResult&gt;
    Case&lt;T1, T2, TResult&gt;(
    this PatternMatcher&lt;Tuple&lt;T1, T2&gt;, TResult&gt; pattern,
    {arg1},
    {arg2},
    Expression&lt;Func&lt;T1, T2, TResult&gt;&gt; selector)</pre>
<p>where the {arg1} and {arg2} placeholders are replaced with :</p>
<ul>
<li>T1 testValue1, T2 testValue2
<li>T1 testValue1, Expression&lt;Func&lt;T2, bool&gt;&gt; testExpression2
<li>T1 testValue1, MatchCase any2
<li>Expression&lt;Func&lt;T1, bool&gt;&gt; testExpression1, T2 testValue2
<li>Expression&lt;Func&lt;T1, bool&gt;&gt; testExpression1, Expression&lt;Func&lt;T2, bool&gt;&gt; testExpression2
<li>Expression&lt;Func&lt;T1, bool&gt;&gt; testExpression1, MatchCase any2
<li>MatchCase any1, T2 testValue2
<li>MatchCase any1, Expression&lt;Func&lt;T2, bool&gt;&gt; testExpression2
<li>MatchCase any1, MatchCase any2 </li>
</ul>
<p>The implementation of each method follows the same pattern as in the previous post, and builds an expression that determines whether a given tuple matches the pattern, returning, and evaluates the selector expression when there is a match.</p>
<p>But if we want to handle tuples with more values… do we have to write all the overloads ?!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/pattern-matching-in-c-part-3-tuples/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pattern matching in C# – part 2</title>
		<link>http://www.pirrmann.net/pattern-matching-in-c-part-2/</link>
		<comments>http://www.pirrmann.net/pattern-matching-in-c-part-2/#comments</comments>
		<pubDate>Tue, 19 Mar 2013 05:00:29 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Functional Inspiration]]></category>
		<category><![CDATA[Syntax Puzzles]]></category>
		<category><![CDATA[AST]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Puzzle]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=196</guid>
		<description><![CDATA[Last time, I just stopped before generating any real expression tree… Now is the perfect time to continue the process ! In order to handle match expressions where none of the expressions would match a given candidate, I decided to &#8230; <a href="http://www.pirrmann.net/pattern-matching-in-c-part-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Last time, I just stopped before generating any real expression tree… Now is the perfect time to continue the process !</p>
<p>In order to handle match expressions where none of the expressions would match a given candidate, I decided to use an option type. This allows the generation of this type of expressions:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">Func&lt;double, Option&lt;double&gt;&gt; matchSomeOrNone =
    (double d) =&gt;
        (d &gt; 0.0)
        ? Option&lt;double&gt;.Some(d)
        : Option&lt;double&gt;.None();</pre>
<p>Given this these options, the translation of last time’s sample code:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var stringPattern = PatternMatcher
    .CreateSwitch&lt;string, double&gt;()
    .Case("TEST"                        , s =&gt; Math.PI)
    .Case("TEST_1"                      , s =&gt; Math.E)
    .Case((string)null                  , s =&gt; 0.0)
    .Case(s =&gt; s.StartsWith("TEST__")   , s =&gt; Math.E * 2)
    .CaseElse(                            s =&gt; s.Length);</pre>
<p>would become:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">Func&lt;string, Option&lt;double&gt;&gt; generatedFuncOption =
    (string s) =&gt;
        (s == "TEST")
            ? Option&lt;double&gt;.Some(Math.PI)
            : (s == "TEST_1")
                ? Option&lt;double&gt;.Some(Math.E)
                : (s == null)
                    ? Option&lt;double&gt;.Some(0.0)
                    : s.StartsWith("TEST__")
                        ? Option&lt;double&gt;.Some(Math.E * 2)
                        : Option&lt;double&gt;.Some(s.Length);</pre>
<p>In order to instantiate option types in LINQ expressions, I have to use the corresponding MethodInfo instances, obtained from reflexion :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">MethodInfo createSomeMethodInfo =
    typeof(Option&lt;TResult&gt;)
        .GetMethod(
            "Some",
            BindingFlags.Public | BindingFlags.Static);

MethodInfo createNoneMethodInfo =
    typeof(Option&lt;TResult&gt;)
        .GetMethod(
            "None",
            BindingFlags.Public | BindingFlags.Static);</pre>
<p>And then, in order to finally build a matching expression, I loop over the match conditions and result selector expressions the following way:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">private Func&lt;TSource, Option&lt;TResult&gt;&gt; BuildPatternMatchingFunc()
{
    ParameterExpression parameter =
        Expression.Parameter(typeof(TSource));

    Expression noneExpression = Expression.Call(
        createNoneMethodInfo);

    Expression caseExpression = noneExpression;

    foreach (var matchCase in this.cases.Reverse())
    {
        caseExpression =
            Expression.Condition(
                Expression.Invoke(
                    matchCase.TestExpression,
                    parameter),
                Expression.Call(
                    createSomeMethodInfo,
                    Expression.Invoke(
                        matchCase.SelectorExpression,
                        parameter)),
                caseExpression);
    }

    return Expression
        .Lambda&lt;Func&lt;TSource, Option&lt;TResult&gt;&gt;&gt;(
            caseExpression,
            parameter)
        .Compile();
}</pre>
<p>The createNoneMethodInfo and createSomeMethodInfo are the MethodInfo corresponding to the generic <em>Option&lt;T&gt;.None()</em> and <em>Option&lt;T&gt;.Some()</em> methods obtained by reflection.</p>
<p>Debugging this kind of expression building can be complicated, particularly without the ability to visualize clearly the expression tree… Hopefully, <a href="http://www.pirrmann.net/linq-provider-an-attempt-part-5/">I have built an expression tree visualizer in the past</a> (I could also have used the easy path and install <a href="http://blogs.msdn.com/b/charlie/archive/2008/02/13/linq-farm-seed-using-the-expression-tree-visualizer.aspx">the classical one</a>) ! From the C# sample again, I can produce the following expression tree:</p>
<div class="syntaxtree" style="margin-bottom: 15px; border-top: black 1px solid; height: 630px; border-right: black 1px solid; overflow-x: auto; overflow-y: hidden; border-bottom: black 1px solid; border-left: black 1px solid">
<div style="width: 2800px">
<ul>
<li><a href="#"><span class="node-name">IIF</span><br />Conditional</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Boolean</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Boolean&gt;</span><br />x =&gt; (x == &#8220;TEST&#8221;)</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">Option&lt;Double&gt;</span><br />Some</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Double</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Double&gt;</span><br />s =&gt; 3,14159265358979</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
</li>
</ul>
<li><a href="#"><span class="node-name">IIF</span><br />Conditional</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Boolean</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Boolean&gt;</span><br />x =&gt; (x == &#8220;TEST_1&#8243;)</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">Option&lt;Double&gt;</span><br />Some</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Double</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Double&gt;</span><br />s =&gt; 2,71828182845905</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
</li>
</ul>
<li><a href="#"><span class="node-name">IIF</span><br />Conditional</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Boolean</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Boolean&gt;</span><br />s =&gt; (Convert(s) == null)</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">Option&lt;Double&gt;</span><br />Some</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Double</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Double&gt;</span><br />s =&gt; 0</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
</li>
</ul>
<li><a href="#"><span class="node-name">IIF</span><br />Conditional</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Boolean</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Boolean&gt;</span><br />s =&gt; s.StartsWith(&#8220;TEST__&#8221;)</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">Option&lt;Double&gt;</span><br />Some</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Double</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Double&gt;</span><br />s =&gt; 5,43656365691809</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
</li>
</ul>
<li><a href="#"><span class="node-name">IIF</span><br />Conditional</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Boolean</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Boolean&gt;</span><br />s =&gt; True</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">Option&lt;Double&gt;</span><br />Some</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Double</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Double&gt;</span><br />s =&gt; Convert(s.Length)</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
</li>
</ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">Option&lt;Double&gt;</span><br />None</a>
<ul></ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<p>This tree may seem wide, but is is just a succession of conditional expressions… Finally, the the function that evaluates the result of the pattern-matching expression is the following one:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public TResult Eval(TSource candidate)
{
    if (this.patternMatchingFunc == null)
    {
        this.patternMatchingFunc = BuildPatternMatchingFunc();
    }

    Option&lt;TResult&gt; matchResult = patternMatchingFunc
                                    .Invoke(candidate);

    if (!matchResult.IsSome)
        throw new NoMatchFoundException();

    return matchResult.Value;
}</pre>
<p>As you can see, it’s a wrapper around the expression evaluation invocation. It first generates the expression&nbsp; instantiates upon the first call (in a non-threadsafe way, but who cares !) and handles “nothing matches” case by throwing an exception. And this works !</p>
<p>Now, you might say that matching a single value in of very limited interest. I can’t deny it. Why don’t we try to match several values, then ?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/pattern-matching-in-c-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pattern matching in C# – part 1</title>
		<link>http://www.pirrmann.net/pattern-matching-in-c-sharp-part-1/</link>
		<comments>http://www.pirrmann.net/pattern-matching-in-c-sharp-part-1/#comments</comments>
		<pubDate>Wed, 27 Feb 2013 20:44:11 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Functional Inspiration]]></category>
		<category><![CDATA[Syntax Puzzles]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Puzzle]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=192</guid>
		<description><![CDATA[In my previous post, I tried to explain what pattern matching is, and in particular the F# match expression, that I’m trying to mimic in C#. For my first attempt, I’ll try to analyse the matching cases that can apply &#8230; <a href="http://www.pirrmann.net/pattern-matching-in-c-sharp-part-1/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>In my <a href="http://www.pirrmann.net/pattern-matching-in-c-sharp-introduction/">previous post</a>, I tried to explain what pattern matching is, and in particular the F# match expression, that I’m trying to mimic in C#. For my first attempt, I’ll try to analyse the matching cases that can apply on a single value. Let’s start right now with an F# sample<sup><a href="#note1">[1]</a></sup>:</p>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let test str =
    match str with
    | "TEST" -&gt; Math.PI
    | "TEST_1" -&gt; Math.E
    | null -&gt; 0.0
    | s when s.StartsWith("TEST__") -&gt; Math.E * 2.0
    | s -&gt; float s.Length</pre>
<p>If we analyse these patterns, we see 3 different cases:</p>
<ul>
<li>a constant pattern (including the null value),
<li>a conditional pattern (the lambda one)
<li>a default pattern (the else case).</li>
</ul>
<p>So in C#, what I’ve managed to build is the following:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var stringPattern = PatternMatcher
.CreateSwitch&lt;string, double&gt;()
.Case("TEST"                        , s =&gt; Math.PI)
.Case("TEST_1"                      , s =&gt; Math.E)
.Case((string)null                  , s =&gt; 0.0)
.Case(s =&gt; s.StartsWith("TEST__")   , s =&gt; Math.E * 2)
.CaseElse(                            s =&gt; s.Length);</pre>
<p>What is difficult here is to write something that is valid C#, because:</p>
<ol>
<li>I can’t change the compiler,
<li>To keep things simple, I don’t want to use Roslyn in the first attempt (although that might come later).</li>
</ol>
<h3>Recording expressions for individual tests</h3>
<p>This solution is mainly based upon a generic class called <em>PatternMatcher&lt;TSource, TResult&gt;</em>, which represents the match expression being built. Each <em>Case</em> overload builds an instance of a <em>MatchCase</em> class. As with many “fluent” syntax nowadays, in order to chain the calls in a single statement, each <em>Case</em> overload returns a new instance of the <em>PatternMatcher</em>, which keeps track of all the cases registered so far.</p>
<p>The <em>MatchCase</em>’s sole purpose is to encapsulate two expressions:</p>
<ul>
<li>a test expression that will be used to determine if a particular source value matches the case: this will be an expression of <em>Func&lt;TSource, bool&gt;</em>,
<li>a selector expression that will be used to produce the result of the match expression when the input value matches this particular case: this will be an expression of <em>Func&lt;TSource, TResult&gt;</em>.</li>
</ul>
<p>Getting an Expression of a given Func type is nothing more that changing the type of a variable. The compiler will change its work accordingly, and produce an Expression from a given lambda-expression, instead of a typed delegate.</p>
<p>The most general case is the conditional pattern. Let’s take a look at the following extension method:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public static PatternMatcher&lt;TSource, TResult&gt;
    Case&lt;TSource, TResult&gt;(
        this PatternMatcher&lt;TSource, TResult&gt; pattern,
        Expression&lt;Func&lt;TSource, bool&gt;&gt; testExpression,
        Expression&lt;Func&lt;TSource, TResult&gt;&gt; selector)</pre>
<p>You can see that the testExpression and selector parameters are already the types that my <em>MatchCase</em> class needs. From this values, I just have to instantiate the class and store it for later use.</p>
<p>The two other&nbsp; cases (constant and default) will also provide directly the selector expression, only the test expression will have to be provided:</p>
<ul>
<li>as an expression that tests equality with a given constant, for the constant pattern,
<li>as an expression that is always true, for the default pattern.</li>
</ul>
<p>These cases are just special cases of the previous one, called with an appropriate lambda, which will be converted to the test expression.</p>
<h3>Building an expression tree</h3>
<p>Of course, what we want to do is more that just record the expressions ! The next step is to combine them in a global match expression.</p>
<p>The kind of code I would like to produce, for the previous sample, would be the following:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">Func&lt;string, double&gt; generatedFunc =
(string s) =&gt;
    {
        if (s == "TEST") return Math.PI;
        if (s == "TEST_1") return Math.E;
        if (s == null) return 0.0;
        if (s.StartsWith("TEST__")) return Math.E * 2;
        return s.Length;
    };</pre>
<p>Or even “better”, the same, but with conditional expressions instead of <em>if</em> and <em>return</em> statements:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">Func&lt;string, double&gt; generatedFuncNoIf =
    (string s) =&gt;
        (s == "TEST")
            ? Math.PI
            : (s == "TEST_1")
                ? Math.E
                : (s == null)
                    ? 0.0
                    : s.StartsWith("TEST__")
                        ? Math.E * 2
                        : s.Length;</pre>
<p>An expression corresponding to the previous code could be generated, but I also want to handle an additional case: when there is no match. This means that my expression has to be able to return some result or… none. <a href="http://www.pirrmann.net/functional-inspiration-a-simple-option-type/">Some or none ? Isn’t there a type for that ?</a> We’ll see how to use it next time.</p>
<p><a name="note1">[1]</a> I know this sample is useless and theoretical, but isn’t this whole series ? If you really want to use match expressions, embrace F#, not C# !</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/pattern-matching-in-c-sharp-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pattern matching in C# – introduction</title>
		<link>http://www.pirrmann.net/pattern-matching-in-c-sharp-introduction/</link>
		<comments>http://www.pirrmann.net/pattern-matching-in-c-sharp-introduction/#comments</comments>
		<pubDate>Wed, 27 Feb 2013 06:06:24 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Functional Inspiration]]></category>
		<category><![CDATA[Syntax Puzzles]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Puzzle]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=190</guid>
		<description><![CDATA[Although bringing real pattern matching to C# in not my objective, I’ve tackled yet another syntax puzzle, trying to build a “sort-of” F#-ish pattern-matching-like syntax. Disclaimer : as you can see from the quotes and italic, don’t expect me to &#8230; <a href="http://www.pirrmann.net/pattern-matching-in-c-sharp-introduction/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Although bringing real pattern matching to C# in not my objective, I’ve tackled yet another syntax puzzle, trying to build a <em>“sort-of” F#-ish pattern-matching-like</em> syntax.<br /> <u>Disclaimer : as you can see from the quotes and italic, don’t expect me to build a fully-functional F# pattern matching in C#.</u></p>
<h3>What is pattern matching ?</h3>
<p>From the <a href="http://msdn.microsoft.com/en-us/library/dd547125.aspx">MSDN entry on Pattern matching</a> :</p>
<blockquote><p>Patterns are rules for transforming input data. They are used throughout the F# language to compare data with a logical structure or structures, decompose data into constituent parts, or extract information from data in various ways.</p>
</blockquote>
<p>The point I want to focus on is in fact the <a href="http://msdn.microsoft.com/en-us/library/dd233242.aspx">F# match expression</a>. The match expression is a powerful way to express conditions over data. It is often described as a “switch statement on steroids”. Its characteristics are the following :</p>
<ul>
<li>Just like a switch, it takes a value as its input,
<li>Unlike a switch, the value is not limited only to enums or built-in value types.
<li>It has a return type. If there is nothing to return, F# uses a special <em>unit</em> type, but there is no <em>void</em> as a return type neither a <em>null</em> value.
<li>If the values to return can be of different types depending on the input, Discriminated Unions (DUs) can be used as return types. </li>
</ul>
<p>I’ll start with a simple F# sample, to show what a discriminated union is :</p>
<pre class="brush: fsharp; gutter: false; toolbar: false;">type Shape =
    | Point
    | Circle of float
    | Rectangle of float * float</pre>
<p>In this sample, a type Shape is defined, that can be either a Point, a Circle or a Rectangle. Although the Point could be considered a simple enum value, the Circle and Rectangle cases, unlike enums, carry data. For instance :</p>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let p = Point
let c = Circle(5.0)
let r = Rectangle(10.0, 20.0)</pre>
<p>If we want to extract the data components of a particular union type, we use pattern-matching in the following way :</p>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let Rectangle(w, h) = r</pre>
<p>This expression binds the value of w and h to the data elements of the r Rectangle defined earlier. But my purpose in the blog series is to introduce in C# a syntax that would look like a match expression, which in F# is the following :</p>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let getArea s =
    match s with
    | Point -&gt; 0.0
    | Circle(r) -&gt; r * r * System.Math.PI
    | Rectangle(w, h) -&gt; w * h</pre>
<p>In this attempt, I first consider matching simple values (which has no practical interest of any sort), then matching tuples, and I’ll finish with matching against some sort of Discriminated Union, although DUs are not a native C# construct.</p>
<p>First, let’s consider what we want to build. From the sample above, we can see that what we get from the match expression is a “<em>getArea</em>” that takes an instance of the union type as input, and gives a float as output. As this is just the definition of a function, it looks like we’re trying to build a construct that generates instances of the generic <em>Func&lt;TInput, TOutput&gt;</em> delegate.</p>
<p>In F#, match expressions can also be used to perform actions, and in this case will return the special <em>unit</em> type. To perform actions in C# we have the <em>Action&lt;T&gt;</em> delegate type. In this series I’ll consider only the functions, but actions could be built exactly the same way.</p>
<p>In <a href="http://www.pirrmann.net/pattern-matching-in-c-sharp-part-1/">the next part</a>, I’ll show my first naive attempt to deal with simple values, before targeting any tuples or discriminated union types.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/pattern-matching-in-c-sharp-introduction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>