Research | Blog | TomasP.Nethttp://tomasp.net/blogBlog2013, Tomas PetricekBlogPower of mathematics: Reasoning about functional typeshttp://tomasp.net/blog/types-and-math.aspxTue, 14 May 2013 17:54:46 GMTIn this article, I explore the amazing relationship between functional data types and algebraic operations. We will use this relationship to reason about domain model and understand the differences between several possible representations.Tomas Petricek<img src="http://tomasp.net/articles/types-and-maths/distributivity.png" class="rdecor" /> <p>One of the most amazing aspects of mathematics is that it applies to such a wide range of areas. The same mathematical rules can be applied to completely different objects (say, forces in physics or markets in economics) and they work exactly the same way.</p> <p>In this article, we'll look at one such fascinating use of mathematics - we'll use elementary school algebra to reason about functional data types.</p> <p>In functional programming, the best way to start solving a problem is to think about the data types that are needed to represent the data that you will be working with. This gives you a simple starting point and a great tool to communicate and develop your ideas. I call this approach <a href="http://tomasp.net/blog/type-first-development.aspx">Type-First Development and I wrote about it earlier</a>, so I won't repeat that here.</p> <p>The two most elementary types in functional languages are <em>tuples</em> (also called pairs or product types) and <em>discriminated unions</em> (also called algebraic data types, case classes or sum types). It turns out that these two types are closely related to <em>multiplication</em> and <em>addition</em> in algebra...</p> F# Data: New type provider libraryhttp://tomasp.net/blog/fsharp-data.aspxThu, 28 Mar 2013 03:23:41 GMTF# Data is a new library that gives you all you need to access data in F# 3.0. It implements type providers for WorldBank, Freebase and structured document formats (CSV, JSON and XML) as well as other helpers. This article introduces the library and gives a quick overview of its features.Tomas Petricek<img src="https://raw.github.com/fsharp/FSharp.Data/master/misc/logo.png" class="rdecor" style="width:120px;height:120px;" /> <p>When F# 3.0 type providers were still in beta version, I wrote a couple of type providers as examples for talks. These included the WorldBank type provider (now available <a href="http://www.tryfsharp.org">on Try F#</a>) and also type provider for XML that infered the structure from sample. <br /> For some time, these were hosted as part of <a href="https://github.com/fsharp/fsharpx/">FSharpX</a> and the authors of FSharpX also added a number of great features.</p> <p>When I found some more time earlier this year, I decided to start a new library that would be fully focused on data access in F# and on type providers and I started working on <strong>F# Data</strong>. The library has now reached a stable state and <a href="http://www.navision-blog.de/blog/2013/03/27/fsharpx-1-8-removes-support-for-document-type-provider/">Steffen also announced</a> that the document type providers (JSON, XML and CSV) are not going to be available in FSharpX since the next version.</p> <p>This means that if you're interested in accessing data using F# type providers, you should now go to F# Data. Here are the most important links:</p> <ul> <li><a href="https://github.com/fsharp/FSharp.Data">F# Data source code on GitHub</a></li> <li><a href="http://fsharp.github.com/FSharp.Data/">F# Data documentation &amp; tutorials</a></li> <li><a href="http://nuget.org/packages/FSharp.Data">F# Data on NuGet</a></li> </ul> <p>Before looking at the details, I would like to thank to <a href="https://github.com/ovatsus">Gustavo Guerra</a> who made some amazing contributions to the library! (More contributors are always welcome, so continue reading if you're interested...)</p> Announcing: Literate programming tools for F#http://tomasp.net/blog/fsharp-literate-programming.aspxTue, 22 Jan 2013 17:35:36 GMTThis article introduces a new F# package that makes it possible to write literate F# programs that combine code with documentation. Given an F# script with a special comments or Markdown document with F# code, you get a nicely formatted HTML that can be used to build documentation or write blogs.Tomas Petricek<img src="http://tomasp.net/articles/fsharp-literate-programming/logo.png" class="rdecor" style="width:120px;height:120px;" /> <p>For some time now, I've been writing my F# blog posts (and other F# articles published elsewhere) by combining F# code snippets and Markdown formatting. In fact, I even wrote a Markdown parser in F# so that I can post-process documents (to generate references etc). You can read about the Markdown parser in an upcoming <a href="http://manning.com/petricek2/">F# Deep Dives</a> book - currently, it is available as a free chapter!</p> <p>During the Christmas break, I finally found enough time to clean-up the code I was using and package it properly into a documented library that is easy to install and use. Here are the most important links:</p> <ul> <li><a href="http://tpetricek.github.com/FSharp.Formatting">F# Formatting home page</a></li> <li><a href="https://github.com/tpetricek/FSharp.Formatting">F# Formatting source code</a> on GitHub</li> <li><a href="https://nuget.org/packages/FSharp.Formatting">F# Formatting package</a> on NuGet</li> </ul> <p>To learn more about the tool and how to use it, <a href="http://tomasp.net/blog/fsharp-literate-programming.aspx">continue reading!</a></p>Processing trees with F# zipper computationhttp://tomasp.net/blog/tree-zipper-query.aspxWed, 19 Dec 2012 14:22:47 GMTOne of the less frequently advertised new features in F# 3.0 is the query syntax. It allows adding custom operations to a computation expression block. This article shows how to define a custom computation for processing trees using zippers. We'll add navigation over a tree as custom operations to get a simple syntax.Tomas Petricek<p>One of the less frequently advertised new features in F# 3.0 is the <em>query syntax</em>. It is an extension that makes it possible to add custom operations in an F# computation expression. The standard <code>query { .. }</code> computation uses this to define operations such as sorting (<code>sortBy</code> and <code>sortByDescending</code>) or operations for taking and skipping elements (<code>take</code>, <code>takeWhile</code>, ...). For example, you can write:</p> <pre class="fssnip"> <span class="l">1: </span><span onmouseout="hideTip(event, 'fstip1', 1)" onmouseover="showTip(event, 'fstip1', 1)" class="i">query</span> { <span class="k">for</span> <span onmouseout="hideTip(event, 'fstip2', 2)" onmouseover="showTip(event, 'fstip2', 2)" class="i">x</span> <span class="k">in</span> <span class="n">1</span> <span class="o">..</span> <span class="n">10</span> <span class="k">do</span> <span class="l">2: </span> <span onmouseout="hideTip(event, 'fstip3', 3)" onmouseover="showTip(event, 'fstip3', 3)" class="k">take</span> <span class="n">3</span> <span class="l">3: </span> <span onmouseout="hideTip(event, 'fstip4', 4)" onmouseover="showTip(event, 'fstip4', 4)" class="k">sortByDescending</span> <span onmouseout="hideTip(event, 'fstip2', 5)" onmouseover="showTip(event, 'fstip2', 5)" class="i">x</span> }</pre> <p>In this article I'll use the same notation for processing trees using the <em>zipper</em> pattern. I'll show how to define a computation that allows you to traverse a tree and perform transformations on (parts) of the tree. For example, we'll be able to say "Go to the left sub-tree, multiply all values by 2. Then go back and to the right sub-tree and divide all values by 2" as follows:</p> <pre class="fssnip"> <span class="l">1: </span><span onmouseout="hideTip(event, 'fsdtip1', 1)" onmouseover="showTip(event, 'fsdtip1', 1)" class="i">tree</span> { <span class="k">for</span> <span onmouseout="hideTip(event, 'fsdtip2', 2)" onmouseover="showTip(event, 'fsdtip2', 2)" class="i">x</span> <span class="k">in</span> <span onmouseout="hideTip(event, 'fsdtip3', 3)" onmouseover="showTip(event, 'fsdtip3', 3)" class="i">sample</span> <span class="k">do</span> <span class="l">2: </span> <span onmouseout="hideTip(event, 'fsdtip4', 4)" onmouseover="showTip(event, 'fsdtip4', 4)" class="k">left</span> <span class="l">3: </span> <span onmouseout="hideTip(event, 'fsdtip5', 5)" onmouseover="showTip(event, 'fsdtip5', 5)" class="k">map</span> (<span onmouseout="hideTip(event, 'fsdtip2', 6)" onmouseover="showTip(event, 'fsdtip2', 6)" class="i">x</span> <span class="o">*</span> <span class="n">2</span>) <span class="l">4: </span> <span onmouseout="hideTip(event, 'fsdtip6', 7)" onmouseover="showTip(event, 'fsdtip6', 7)" class="k">up</span> <span class="l">5: </span> <span onmouseout="hideTip(event, 'fsdtip7', 8)" onmouseover="showTip(event, 'fsdtip7', 8)" class="k">right</span> <span class="l">6: </span> <span onmouseout="hideTip(event, 'fsdtip5', 9)" onmouseover="showTip(event, 'fsdtip5', 9)" class="k">map</span> (<span onmouseout="hideTip(event, 'fsdtip2', 10)" onmouseover="showTip(event, 'fsdtip2', 10)" class="i">x</span> <span class="o">/</span> <span class="n">2</span>) <span class="l">7: </span> <span onmouseout="hideTip(event, 'fsdtip8', 11)" onmouseover="showTip(event, 'fsdtip8', 11)" class="k">top</span> }</pre> <p>This example behaves quite differently to the usual <code>query</code> computation. It mostly relies on custom operations like <code>left</code>, <code>right</code> and <code>up</code> that allow us to navigate through a tree (descend along the left or right sub-tree, go back to the parent node). The only operation that <em>does something</em> is the <code>map</code> operation which transforms the current sub-tree.</p> <p>This was just a brief introduction to what is possible, so let's take a detailed look at how this works...</p> <!-- HTML for Tool Tips --> <div class="tip" id="fstip1">val query : Linq.QueryBuilder<br /><br />Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.query</div> <div class="tip" id="fstip2">val x : int</div> <div class="tip" id="fstip3">custom operation: take (int)<br /><br />Calls Linq.QueryBuilder.Take </div> <div class="tip" id="fstip4">custom operation: sortByDescending ('Key)<br /><br />Calls Linq.QueryBuilder.SortByDescending </div> <div class="tip" id="fstip5">type Tree&lt;'T&gt; =<br />  | Node of Tree&lt;'T&gt; * Tree&lt;'T&gt;<br />  | Leaf of 'T<br />  override ToString : unit -&gt; string<br /><br />Full name: Tree-zipper-query.Tree&lt;_&gt;</div> <div class="tip" id="fstip6">union case Tree.Node: Tree&lt;'T&gt; * Tree&lt;'T&gt; -&gt; Tree&lt;'T&gt;</div> <div class="tip" id="fstip7">union case Tree.Leaf: 'T -&gt; Tree&lt;'T&gt;</div> <div class="tip" id="fstip8">val x : Tree&lt;'T&gt;</div> <div class="tip" id="fstip9">override Tree.ToString : unit -&gt; string<br /><br />Full name: Tree-zipper-query.Tree`1.ToString</div> <div class="tip" id="fstip10">match x with<br />    | Node(l, r) -&gt; sprintf "(%O, %O)" l r<br />    | Leaf v -&gt; sprintf "%O" v</div> <div class="tip" id="fstip11">type Path&lt;'T&gt; =<br />  | Top<br />  | Left of Path&lt;'T&gt; * Tree&lt;'T&gt;<br />  | Right of Path&lt;'T&gt; * Tree&lt;'T&gt;<br />  override ToString : unit -&gt; string<br /><br />Full name: Tree-zipper-query.Path&lt;_&gt;</div> <div class="tip" id="fstip12">union case Path.Top: Path&lt;'T&gt;</div> <div class="tip" id="fstip13">union case Path.Left: Path&lt;'T&gt; * Tree&lt;'T&gt; -&gt; Path&lt;'T&gt;</div> <div class="tip" id="fstip14">union case Path.Right: Path&lt;'T&gt; * Tree&lt;'T&gt; -&gt; Path&lt;'T&gt;</div> <div class="tip" id="fstip15">val x : Path&lt;'T&gt;</div> <div class="tip" id="fstip16">override Path.ToString : unit -&gt; string<br /><br />Full name: Tree-zipper-query.Path`1.ToString</div> <div class="tip" id="fstip17">match x with<br />    | Top -&gt; "T"<br />    | Left(p, t) -&gt; sprintf "L(%O, %O)" p t<br />    | Right(p, t) -&gt; sprintf "R(%O, %O)" p t</div> <div class="tip" id="fstip18">type TreeZipper&lt;'T&gt; =<br />  | TZ of Tree&lt;'T&gt; * Path&lt;'T&gt;<br />  override ToString : unit -&gt; string<br /><br />Full name: Tree-zipper-query.TreeZipper&lt;_&gt;</div> <div class="tip" id="fstip19">union case TreeZipper.TZ: Tree&lt;'T&gt; * Path&lt;'T&gt; -&gt; TreeZipper&lt;'T&gt;</div> <div class="tip" id="fstip20">val x : TreeZipper&lt;'T&gt;</div> <div class="tip" id="fstip21">override TreeZipper.ToString : unit -&gt; string<br /><br />Full name: Tree-zipper-query.TreeZipper`1.ToString</div> <div class="tip" id="fstip22">let (TZ(t, p)) = x in sprintf "%O [%O]" t p</div> <div class="tip" id="fstip23">val left : _arg1:TreeZipper&lt;'a&gt; -&gt; TreeZipper&lt;'a&gt;<br /><br />Full name: Tree-zipper-query.left<br /><em><br /><br /> Navigates to the left sub-tree</em></div> <div class="tip" id="fstip24">val failwith : message:string -&gt; 'T<br /><br />Full name: Microsoft.FSharp.Core.Operators.failwith</div> <div class="tip" id="fstip25">val l : Tree&lt;'a&gt;</div> <div class="tip" id="fstip26">val r : Tree&lt;'a&gt;</div> <div class="tip" id="fstip27">val p : Path&lt;'a&gt;</div> <div class="tip" id="fstip28">val right : _arg1:TreeZipper&lt;'a&gt; -&gt; TreeZipper&lt;'a&gt;<br /><br />Full name: Tree-zipper-query.right<br /><em><br /><br /> Navigates to the right sub-tree</em></div> <div class="tip" id="fstip29">val current : _arg1:TreeZipper&lt;'a&gt; -&gt; 'a<br /><br />Full name: Tree-zipper-query.current<br /><em><br /><br /> Gets the value at the current position</em></div> <div class="tip" id="fstip30">val x : 'a</div> <div class="tip" id="fstip31">val branches : Tree&lt;int&gt;<br /><br />Full name: Tree-zipper-query.branches</div> <div class="tip" id="fstip32">val sample : TreeZipper&lt;int&gt;<br /><br />Full name: Tree-zipper-query.sample</div> <div class="tip" id="fstip33">val printfn : format:Printf.TextWriterFormat&lt;'T&gt; -&gt; 'T<br /><br />Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn</div> <div class="tip" id="fstip34">val up : _arg1:TreeZipper&lt;'a&gt; -&gt; TreeZipper&lt;'a&gt;<br /><br />Full name: Tree-zipper-query.up</div> <div class="tip" id="fstip35">val top : _arg1:TreeZipper&lt;'a&gt; -&gt; TreeZipper&lt;'a&gt;<br /><br />Full name: Tree-zipper-query.top</div> <div class="tip" id="fstip36">val t : TreeZipper&lt;'a&gt;</div> <div class="tip" id="fstip37">val tz : TreeZipper&lt;'a&gt;</div> <div class="tip" id="fstip38">Multiple items<br />val unit : v:'a -&gt; TreeZipper&lt;'a&gt;<br /><br />Full name: Tree-zipper-query.unit<br /><em><br /><br /> Build tree zipper with singleton tree</em><br /><br />--------------------<br />type unit = Unit<br /><br />Full name: Microsoft.FSharp.Core.unit</div> <div class="tip" id="fstip39">val v : 'a</div> <div class="tip" id="fstip40">val bindSub : f:('a -&gt; TreeZipper&lt;'a&gt;) -&gt; treeZip:TreeZipper&lt;'a&gt; -&gt; TreeZipper&lt;'a&gt;<br /><br />Full name: Tree-zipper-query.bindSub<br /><em><br /><br /> Transform leaves in the current sub-tree of 'treeZip'<br /> into other trees using the provided function 'f'</em></div> <div class="tip" id="fstip41">val f : ('a -&gt; TreeZipper&lt;'a&gt;)</div> <div class="tip" id="fstip42">val treeZip : TreeZipper&lt;'a&gt;</div> <div class="tip" id="fstip43">val bindT : (Tree&lt;'a&gt; -&gt; Tree&lt;'a&gt;)</div> <div class="tip" id="fstip44">val t : Tree&lt;'a&gt;</div> <div class="tip" id="fstip45">val current : Tree&lt;'a&gt;</div> <div class="tip" id="fstip46">val path : Path&lt;'a&gt;</div> <div class="tip" id="fstip47">Multiple items<br />type TreeZipperBuilder =<br />  new : unit -&gt; TreeZipperBuilder<br />  member Current : tz:TreeZipper&lt;'a&gt; -&gt; 'a<br />  member For : tz:TreeZipper&lt;'T&gt; * f:('T -&gt; TreeZipper&lt;'T&gt;) -&gt; TreeZipper&lt;'T&gt;<br />  member Left : tz:TreeZipper&lt;'a&gt; -&gt; TreeZipper&lt;'a&gt;<br />  member Right : tz:TreeZipper&lt;'a&gt; -&gt; TreeZipper&lt;'a&gt;<br />  member Select : tz:TreeZipper&lt;'a&gt; * f:('a -&gt; 'a) -&gt; TreeZipper&lt;'a&gt;<br />  member Top : tz:TreeZipper&lt;'a&gt; -&gt; TreeZipper&lt;'a&gt;<br />  member Up : tz:TreeZipper&lt;'a&gt; -&gt; TreeZipper&lt;'a&gt;<br />  member Yield : v:'a -&gt; TreeZipper&lt;'a&gt;<br /><br />Full name: Tree-zipper-query.TreeZipperBuilder<br /><br />--------------------<br />new : unit -&gt; TreeZipperBuilder</div> <div class="tip" id="fstip48">val x : TreeZipperBuilder</div> <div class="tip" id="fstip49">member TreeZipperBuilder.For : tz:TreeZipper&lt;'T&gt; * f:('T -&gt; TreeZipper&lt;'T&gt;) -&gt; TreeZipper&lt;'T&gt;<br /><br />Full name: Tree-zipper-query.TreeZipperBuilder.For<br /><em><br /><br /> Enables the 'for x in xs do ..' syntax</em></div> <div class="tip" id="fstip50">val tz : TreeZipper&lt;'T&gt;</div> <div class="tip" id="fstip51">val f : ('T -&gt; TreeZipper&lt;'T&gt;)</div> <div class="tip" id="fstip52">member TreeZipperBuilder.Yield : v:'a -&gt; TreeZipper&lt;'a&gt;<br /><br />Full name: Tree-zipper-query.TreeZipperBuilder.Yield<br /><em><br /><br /> Enables the 'yield x' syntax</em></div> <div class="tip" id="fstip53">val tree : TreeZipperBuilder<br /><br />Full name: Tree-zipper-query.tree<br /><em><br /><br /> Global instance of the computation builder</em></div> <div class="tip" id="fstip54">Multiple items<br />type CustomOperationAttribute =<br />  inherit Attribute<br />  new : name:string -&gt; CustomOperationAttribute<br />  member AllowIntoPattern : bool<br />  member IsLikeGroupJoin : bool<br />  member IsLikeJoin : bool<br />  member IsLikeZip : bool<br />  member JoinConditionWord : string<br />  member MaintainsVariableSpace : bool<br />  member MaintainsVariableSpaceUsingBind : bool<br />  member Name : string<br />  ...<br /><br />Full name: Microsoft.FSharp.Core.CustomOperationAttribute<br /><br />--------------------<br />new : name:string -&gt; CustomOperationAttribute</div> <div class="tip" id="fstip55">member TreeZipperBuilder.Left : tz:TreeZipper&lt;'a&gt; -&gt; TreeZipper&lt;'a&gt;<br /><br />Full name: Tree-zipper-query.TreeZipperBuilder.Left</div> <div class="tip" id="fstip56">member TreeZipperBuilder.Right : tz:TreeZipper&lt;'a&gt; -&gt; TreeZipper&lt;'a&gt;<br /><br />Full name: Tree-zipper-query.TreeZipperBuilder.Right</div> <div class="tip" id="fstip57">member TreeZipperBuilder.Up : tz:TreeZipper&lt;'a&gt; -&gt; TreeZipper&lt;'a&gt;<br /><br />Full name: Tree-zipper-query.TreeZipperBuilder.Up</div> <div class="tip" id="fstip58">member TreeZipperBuilder.Top : tz:TreeZipper&lt;'a&gt; -&gt; TreeZipper&lt;'a&gt;<br /><br />Full name: Tree-zipper-query.TreeZipperBuilder.Top</div> <div class="tip" id="fstip59">member TreeZipperBuilder.Current : tz:TreeZipper&lt;'a&gt; -&gt; 'a<br /><br />Full name: Tree-zipper-query.TreeZipperBuilder.Current<br /><em><br /><br /> Extracts the current value and returns it</em></div> <div class="tip" id="fstip60">member TreeZipperBuilder.Select : tz:TreeZipper&lt;'a&gt; * f:('a -&gt; 'a) -&gt; TreeZipper&lt;'a&gt;<br /><br />Full name: Tree-zipper-query.TreeZipperBuilder.Select<br /><em><br /><br /> Transform the current sub-tree using 'f'</em></div> <div class="tip" id="fstip61">Multiple items<br />type ProjectionParameterAttribute =<br />  inherit Attribute<br />  new : unit -&gt; ProjectionParameterAttribute<br /><br />Full name: Microsoft.FSharp.Core.ProjectionParameterAttribute<br /><br />--------------------<br />new : unit -&gt; ProjectionParameterAttribute</div> <div class="tip" id="fstip62">val f : ('a -&gt; 'a)</div> <div class="tip" id="fstip63">custom operation: right<br /><br />Calls TreeZipperBuilder.Right </div> <div class="tip" id="fstip64">custom operation: left<br /><br />Calls TreeZipperBuilder.Left </div> <div class="tip" id="fstip65">custom operation: current<br /><br />Calls TreeZipperBuilder.Current <br /><em><br /><br /> Extracts the current value and returns it</em></div> <div class="tip" id="fstip66">custom operation: map ('a)<br /><br />Calls TreeZipperBuilder.Select <br /><em><br /><br /> Transform the current sub-tree using 'f'</em></div> <div class="tip" id="fstip67">custom operation: up<br /><br />Calls TreeZipperBuilder.Up </div> <div class="tip" id="fstip68">custom operation: top<br /><br />Calls TreeZipperBuilder.Top </div> <div class="tip" id="fsdtip1">val tree : TreeZipperBuilder<br /><br />Full name: Tree-zipper-query.tree<br /><em><br /><br /> Global instance of the computation builder</em></div> <div class="tip" id="fsdtip2">val x : int</div> <div class="tip" id="fsdtip3">val sample : TreeZipper&lt;int&gt;<br /><br />Full name: Tree-zipper-query.sample</div> <div class="tip" id="fsdtip4">custom operation: left<br /><br />Calls TreeZipperBuilder.Left </div> <div class="tip" id="fsdtip5">custom operation: map ('a)<br /><br />Calls TreeZipperBuilder.Select <br /><em><br /><br /> Transform the current sub-tree using 'f'</em></div> <div class="tip" id="fsdtip6">custom operation: up<br /><br />Calls TreeZipperBuilder.Up </div> <div class="tip" id="fsdtip7">custom operation: right<br /><br />Calls TreeZipperBuilder.Right </div> <div class="tip" id="fsdtip8">custom operation: top<br /><br />Calls TreeZipperBuilder.Top </div> Applicative functors: definition and syntaxhttp://tomasp.net/blog/applicative-functors.aspxTue, 21 Aug 2012 14:23:19 GMTIn a recent blog post, Edward Z. Yang talks about applicative functors. He mentions two equivalent definitions - the standard one used in Haskell and an alternative mentioned in the original paper. In this blog post, I describe some reasons why the alternative definition is useful.Tomas Petricek<p>In a recent blog post, <a href="http://blog.ezyang.com/2012/08/applicative-functors/" title="Edward Z. Yang: Applicative functors">Edward Z. Yang talks about applicative functors</a>. He mentions two equivalent definitions of applicative functors - the standard definition used in Haskell libraries (<code>Applicative</code>) and an alternative that has been also presented in the <a href="http://www.soi.city.ac.uk/~ross/papers/Applicative.html" title="C. McBride and R. Paterson: Applicative Programming with Effects">original paper</a>, but is generally less familiar (<code>Monoidal</code>).</p> <p>The standard definition makes a perfect sense with the standard uses in Haskell, however I always preferred the alternative definition. Edward uses the alternative (<code>Monoidal</code>) definition to explain the laws that should hold about applicative functors and to explain <em>commutative</em> applicative functors, but I think it is even more useful.</p> <p>The <code>Monoidal</code> definition fits nicely with a trick that you can use to <a href="http://tomasp.net/blog/idioms-in-linq.aspx" title="T. Petricek: Beyond the Monad fashion (I.): Writing idioms in LINQ">encode applicative functors in C# using LINQ</a> and I also used it as a basis for an F# syntax extension that allows writing code using applicative functors in a similar style as using monads (which is discussed in my draft paper about <a href="http://www.cl.cam.ac.uk/~tp322/papers/notations.html" title="T. Petricek and D. Syme: Syntax Matters: Writing abstract computations in F#">writing abstract computations in F#</a>). And I also think that <em>commutative</em> applicative functors deserve more attention.</p>Why type-first development mattershttp://tomasp.net/blog/type-first-development.aspxThu, 16 Aug 2012 00:21:21 GMTThis article describes type-first development (TFD). A software development methodology that is quite common among functional programmers and uses types as a simple way of communicating ideas about program design.Tomas Petricek<img src="http://tomasp.net/articles/type-first-development/tfd.png" class="rdecor" /> <p>Using functional programming language changes the way you write code in a number of ways. Many of the changes are at a <em>small-scale</em>. For example, you learn how to express computations in a shorter, more declarative way using higher-order functions. However, there are also many changes at a <em>large-scale</em>. The most notable one is that, when designing a program, you start thinking about the (data) types that represent the data your code works with.</p> <p>In this article, I describe this approach. Since the acronym TDD is already taken, I call the approach Type-First Development (TFD), which is probably a better name anyway. The development is not <em>driven</em> by types. It <em>starts</em> with types, but the rest of the implementation can still use test-driven development for the implementation.</p> <p>This article demonstrates the approach using a case study from a real life: My example is a project that I started working on with a friend who needed a system to log journeys with a company car (for expense reports). Using the type-first approach made it easier to understand and discuss the problem.</p> <p>In many ways, TFD is a very simple approach, so this article just gives a name to a practice that is quite common among functional and F# programmers (and we have been <a href="http://functional-programming.net/courses/">teaching it at our F# trainings</a> for the last year)...</p>The theory behind covariance and contravariance in C# 4http://tomasp.net/blog/variance-explained.aspxTue, 19 Jun 2012 14:24:52 GMTCovariance and contravariance are two useful features of generics in C# 4.0. Most of the time you don't see them. They just let you write code that you'd expect to work. Actually understanding how they work is more difficult. In this article, I explain that, together with some theory where the two concepts come from.Tomas Petricek<img src="http://tomasp.net/articles/variance-explained/icon.png" title="Category theory is sometimes called 'general abstract nonsense', but it can actually be useful!" class="rdecor" /> <p>In C# 4.0, we can annotate generic type parameters with <code>out</code> and <code>in</code> annotations to specify whether they should behave <em>covariantly</em> or <em>contravariantly</em>. This is mainly useful when using already defined standard interfaces. Covariance means that you can use <code>IEnumerable&lt;string&gt;</code> in place where <code>IEnumerable&lt;object&gt;</code> is expected. Contravariance allows you to pass <code>IComparable&lt;object&gt;</code> as an argument of a method taking <code>IComparable&lt;string&gt;</code>.</p> <p>So far, so good. If you already learned about covariance and contravariance in C# 4, then the above two examples are probably familiar. If you're new to the concepts, then the examples should make sense (after a bit of thinking, but I'll say more about them). However, there is still a number of questions. Is there some easy way to explain the two concepts? Why one option makes sense for some types and the other for different types? And why the hell is it called <em>covariance</em> and <em>contravariance</em> anyway?</p> <p>In this blog post, I'll explain some of the mathematics that you can use to think about covariance and contravariance.</p> F# in Academia: Present at upcoming events!http://tomasp.net/blog/fsharp-academia.aspxMon, 16 Apr 2012 00:19:04 GMTThe F# language combines the best from practice and academia. If you're working on interesting application of F#, have an experience worth sharing or some interesting research or idea, there are two workshops where you can share the idea with wider research and practitioner community, so consider submitting a talk!Tomas Petricek<p>The F# language was born as a combination of the pragmatic and real-world .NET platform and functional programming, which had a long tradition in academia. Many useful ideas or libraries in F# (like <em>asynchronous workflows</em> and <em>first-class events</em>) are inspored by research in functional programming (namely, the work on <em>monads</em>, <em>continuations</em> and <em>functional reactive programming</em>).</p> <p>Exchanging the ideas between the research community and the real-world is one of the areas where F# excels. Indeed, the first applicatiosn of F# inside Microsoft (in the Machine Learning group at Cambridge) were all about this - combining research in machine learning with a language that can be easily used in practice.</p> <p>However, F# and the F# users also made numerous contributions to the programming langauge research community. Influential ideas that come from F# include <em>active patterns</em> and the F# style of <em>meta-programming</em> for translating F# to JavaScript). I think there is a lot more that the academic community can learn from the F# community, so I'd like to invite you to talk about your ideas at two upcoming academic events!</p> <p>What, why, when, where and how? <a href="http://tomasp.net/blog/fsharp-academia.aspx">Continue reading!</a></p>TryJoinads (VII.) - Implementing joinads for async workflowshttp://tomasp.net/blog/joinads-async-implement.aspxFri, 23 Mar 2012 17:21:51 GMTIn the final article of the TryJoinads series, I discuss how to implement the joinad structure for F# asynchronous workflows. The article also demonstrates the importance of aliasing for <code>match!</code> notation.Tomas Petricek<p>The article <a href="http://tomasp.net/blog/joinads-async-prog.aspx">Asynchronous workflows and joinads</a> gives numerous examples of programming with asynchronous workflows using the <code>match!</code> construct. Briefly, when matching on multiple asynchronous workflows, they are executed in parallel. When pattern matching consists of multiple clauses, the clause that matches on computations that complete first gets executed. These two behaviours are implemented by the <code>Merge</code> and the <code>Choose</code> operation of joinads. Additionally, asynchronous workflows require the <code>Alias</code> operation, which makes it possible to share the result of a started asynchronous workflow in multiple clauses.</p> <p>In this article, we look at the definition of the additional <code>AsyncBuilder</code> operations that enable the <code>match!</code> syntax. We do not look at additional examples of using the syntax, because these can be <a href="http://tomasp.net/blog/joinads-async-prog.aspx">found in a previous article</a>.</p> <p><em><strong>Note:</strong> This blog post is a re-publication of a tutorial from the <a href="http://tryjoinads.org">TryJoinads.org</a> web page. If you read the article there, you can run the examples interactively and experiment with them: <a href="http://tryjoinads.org/index.html?implement/async.html">view the article on TryJoinads</a>.</em></p> TryJoinads (VI.) - Parsing with joinadshttp://tomasp.net/blog/joinads-parsing.aspxWed, 21 Mar 2012 16:27:06 GMTThis article shows how to use joinads (and the <code>match!</code> extension) for writing parsers. Using joinads one can easily express choice and write a parser that recognizes an intersection of languages.Tomas Petricek<p>In functional programming, parser combinators are a powerful way of writing parsers. A parser is a function that, given some input, returns possible parsed values and the rest of the input. Parsers can be written using combinators for composition, for example run two parsers in sequence or perform one parser any number of times.</p> <p>Parsers can also implement the monad structure. In some cases, this makes the parser less efficient, but it is an elegant way of composing parsers and we can also benefit from the syntactic support for monads. In this article, we implement a simple parser combinators for F# and we look what additional expressive power we can get from the <em>joinad</em> structure and <code>match!</code> construct. This article is largely based on a previous article <em>"Fun with Parallel Monad Comprehensions"</em>, which can be found on the <a href="../pubs.html">publications</a> page.</p> <p><em><strong>Note:</strong> This blog post is a re-publication of a tutorial from the <a href="http://tryjoinads.org">TryJoinads.org</a> web page. If you read the article there, you can run the examples interactively and experiment with them: <a href="http://tryjoinads.org/index.html?implement/parsers.html">view the article on TryJoinads</a>.</em></p> TryJoinads (V.) - Implementing the option joinadhttp://tomasp.net/blog/joinads-options.aspxFri, 02 Mar 2012 13:24:21 GMTThe <code>match!</code> research extension for F# can be used to program with a number of monadic computations. In this article, we look how to support it in one of the simplest monads - the maybe monad.Tomas Petricek<p>This article shows how to implement the <em>joinad</em> structure for one of the simplest monads - the <code>option&lt;'T&gt;</code> type. This is a slightly oversimplified example. The <code>match!</code> construct can be used to write patterns that specify that a monadic value (in this case <code>option&lt;'T&gt;</code>) should contain a certain value, or we can specify that we do not require a value. When working with options, this means the same thing as matching the value against <code>Some</code> and against <code>_</code>, respectively.</p> <p>However, the example demonstrates the operations that need to be implemented and their type signatures. Later articles give more interesting examples including parsers and asynchronous workflows (and you can explore other examples if you look at the <a href="https://github.com/tpetricek/FSharp.Joinads">FSharp.Joiands source code</a> at GitHub).</p> <p><em><strong>Note:</strong> This blog post is a re-publication of a tutorial from the <a href="http://tryjoinads.org">TryJoinads.org</a> web page. If you read the article there, you can run the examples interactively and experiment with them: <a href="http://tryjoinads.org/index.html?implement/options.html">view the article on TryJoinads</a>.</em></p> TryJoinads (IV.) - Concurrency using join calculushttp://tomasp.net/blog/joinads-join-calculus.aspxWed, 22 Feb 2012 17:38:40 GMTThis article shows another application of the <code>match!</code> language extension for F#. This time, we look how to encode join calculus, which is an elegant abstraction for declarative concurrent programming.Tomas Petricek<p>Join calculus provides a declarative way of expressing asynchronous synchronization patterns. It has been use as a basis for programming languages (JoCaml and COmega), but also as a basis for libraries (embedded in C# and Scala). Using joinads, it is possible to embed join calculus in F# with a nice syntax using the <code>match!</code> construct. Formally, join calculus does not form a <em>monad</em>, but it can be viewed as a version of <em>joinad</em> as described in the <a href="../pubs.html">first paper on joinads</a>.</p> <p>The programming model is based on <em>channels</em> and <em>join patterns</em>. A channel can be viewed as a thread-safe mailbox into which we can put values without blocking the caller. In some sense, this is quite similar to <a href="agents.html">F# agents</a>. A join pattern is then a rule saying that a certain combination of values in channels should trigger a specific reaction (and remove values from the channels). The ability to match on multiple channels distinguishes join calculus from F# agents.</p> <p><em><strong>Note:</strong> This blog post is a re-publication of a tutorial from the <a href="http://tryjoinads.org">TryJoinads.org</a> web page. If you read the article there, you can run the examples interactively and experiment with them: <a href="http://tryjoinads.org/index.html?use/joins.html">view the article on TryJoinads</a>.</em></p> TryJoinads (III.): Agent-based programminghttp://tomasp.net/blog/joinads-agents.aspxMon, 20 Feb 2012 12:36:10 GMTAgent-based programming is a great way to write concurrent applications without the usual threading issues. In this article, we look how the "match!" research extension for F# simplifies writing agents. In particular, we can easily implement states that do not handle all incoming messages.Tomas Petricek<p>Another area where the <code>match!</code> syntax can be used is when programming with F# <em>agents</em>, implemented by the <code>MailboxProcessor</code> type. Formally, agents do not form the monad structure in a useful way - when programming with agents, we do not compose a new agents, but instead we write code that (imperatively) receives messages from the agent's mailbox and handles them.</p> <p>This article demonstrates an <code>agent { ... }</code> computation builder that can be used for implementing the body of an agent. Normally, the body of an agent is an <em>asynchronous workflow</em>. The code in the body uses <code>let!</code> to perform asynchronous operations, most importantly to call <code>inbox.Receive</code> to get the next message from the inbox. When the agent intends to handle only certain kinds of messages, it can use <code>inbox.Scan</code>. When using the <code>agent</code> builder, pattern matching on messages can be written using <code>match!</code> and it is possible to write code that ignores certain types of messages simply by writing an incomplete pattern matching.</p> <p><em><strong>Note:</strong> This blog post is a re-publication of a tutorial from the <a href="http://tryjoinads.org">TryJoinads.org</a> web page. If you read the article there, you can run the examples interactively and experiment with them: <a href="http://tryjoinads.org/index.html?use/agents.html">view the article on TryJoinads</a>.</em></p> TryJoinads (II.): Task-based parallelismhttp://tomasp.net/blog/joinad-tasks.aspxFri, 17 Feb 2012 13:10:29 GMTJoinads is a research extension of the F# compiler that makes computation expressions more expressive. In this article, we look how to use the <code>match!</code> notation for working with tasks. The examples include simple parallel map, but also more powerful speculative parallelism.Tomas Petricek<p>The implementation of joinad operations for the <code>Task&lt;'T&gt;</code> type is quite similar to the implementation of <code>Async&lt;'T&gt;</code>, because the two types have similar properties. They both produce at most one value (or an exception) and they both take some time to complete.</p> <p>Just like for asynchronous workflows, pattern matching on multiple computations using <code>match!</code> gives us a parallel composition (with the two tasks running in parallel) and choice between clauses is non-deterministic, depending on which clause completes first.</p> <p>Unlike asynchronous workflows, the <code>Task&lt;'T&gt;</code> type does not require any support for aliasing. A value of type <code>Task&lt;'T&gt;</code> represents a <em>running</em> computation that can be accessed from multiple parts of program. In this sense, the type <code>Async&lt;'T&gt;</code> is more similar to a function <code>unit -&gt; Task&lt;'T&gt;</code> than to the type <code>Task&lt;'T&gt;</code> itself.</p> <p>The key difference between tasks and asynchronous workflows is that the latter provides better support for writing non-blocking computations that involve <em>asynchronous</em> long-running operations such as I/O or waiting for a certain event. Tasks are more suitable for high-performance CPU-intensive computations.</p> <p><em><strong>Note:</strong> This blog post is a re-publication of a tutorial from the <a href="http://tryjoinads.org">TryJoinads.org</a> web page. If you read the article there, you can run the examples interactively and experiment with them: <a href="http://tryjoinads.org/index.html?use/tasks.html">view the article on TryJoinads</a>.</em></p> TryJoinads (I.) - Asynchronous programminghttp://tomasp.net/blog/joinads-async-prog.aspxMon, 13 Feb 2012 17:35:44 GMTThis article demonstrates the new expressive power that joinads add to F# asynchronous workflows. The match! syntax can be used for parallel composition, as well as choice, in a wide range of areas.Tomas Petricek<p>Asynchronous workflows provide a way of writing code that does not block a thread when waiting for a completion of long-running operation such as web service call, another I/O operation or waiting for the completion of some background operation. In this article, we look at the new expressive power that <em>joinads</em> add to asynchronous workflows written using the <code>async { ... }</code> block in F#.</p> <p><em><strong>Note:</strong> This blog post is a re-publication of a tutorial from the <a href="http://tryjoinads.org">TryJoinads.org</a> web page. If you read the article there, you can run the examples interactively and experiment with them: <a href="http://tryjoinads.org/index.html?use/async.html">view the article on TryJoinads</a>.</em></p> Introducing TryJoinads.orghttp://tomasp.net/blog/introducing-tryjoinads.aspxMon, 13 Feb 2012 16:21:03 GMTJoinads is a research extension of F# computation expressions that makes them more useful for parallel, concurrent and reactive programming. This article announces a web site TryJoinads.org where you can experiment with the extension using a web-based F# console.Tomas Petricek<div class="rdecor" style="text-align:center"> <a href="http://tomasp.net/articles/introducing-tryjoinads/screen.png" target="_blank"> <img src="http://tomasp.net/articles/introducing-tryjoinads/screen-sm.png" alt="TryJoinads.Org web site" style="border:none" /> </a><br /> <small>(<a href="http://tomasp.net/articles/introducing-tryjoinads/screen.png" target="_blank">Click for a larger version</a>)</small> </div> <p>If you have been following my blog, you've probably already heard of <em>joinads</em>. It is a research extension of F# computation expressions (or monads in Haskell). The extension makes computation expressions more useful in domains like parallel, concurrent and reactive programming. However, it can be used for any type of computation including, for example, parsers. If you're interested in detailed description, you can find it in two academic papers that I blogged about previously: <a href="http://tomasp.net/blog/match-bang-paper.aspx">PADL 2011</a> and <a href="http://tomasp.net/blog/docase-haskell.aspx">Haskell 2011</a>.</p> <p>The extension adds a keyword <code>match!</code> - as the syntax suggests, it is akin to pattern matching using <code>match</code>, but instead of pattern matching on values, you can pattern match on computations like <code>Async&lt;'T&gt;</code> (or on other monadic values). Just like other features of computation expressions, the <code>match!</code> syntax is translated to applications of several methods defined by the computation builder.</p> <p>I won't say more about joinads in this post, because you can now easily try joinads yourself...</p>Programming with F# asynchronous sequenceshttp://tomasp.net/blog/async-sequences.aspxThu, 11 Aug 2011 23:30:57 GMTAsynchronous sequences provide a way to represent asynchronous computation that generates multiple values on demand. This article defines asynchronous sequences, combinators for working with them and "asyncSeq" computation builder. Then it implements several examples including a sequential asynchronous Web Crawler.Tomas Petricek<img src="http://tomasp.net/articles/async-sequences/decor.png" class="rdecor" /> <p>In F#, we can represent asynchronous operations that do not block threads and eventually return a value of type <code>'T</code> using asynchronous workflows <code>Async&lt;'T&gt;</code>. Asynchronous workflows can be easily constructed using the computation expression syntax <code>async { ... }</code> and there are also a few combi­nators that express more advanced composition (such as parallel composition or fork-join parallelism).</p> <p>Sometimes, we need to use asynchronous operations that return more than just one value. For example, when downloading data from the internet, we would like to create an <em>asynchronous sequence</em> that returns the data in chunks as they become available.</p> <p>One way to represent asynchronous operations that produce multiple values is to use the <code>IObservable&lt;'T&gt;</code> type from .NET. This isn't always the best option though. Observables implement <em>push-based</em> model, which means that chunks of data are generated as quickly as possible (until all chunks are emitted). What if we wanted to take the chunks one-by-one after the previous chunk is processed?</p> <p>In this article, I describe <em>asynchronous sequences</em>. An asynchronous sequence is a simple, yet very powerful concept based on asynchronous workflows. It follows the same core model: results are generated on demand and asynchronously. Unlike asynchronous workflows, asynchronous sequences can be called (on demand) to generate multiple values until the end of the sequence is reached.</p> <p style="font-style:italic">I first discussed asynchronous sequences with Don Syme, Dmitry Lomov and Brian McNamara in an email thread a long time ago. Thanks to Don for enthusiasm about the concept and for the first implementation of some of the combinators!</p> Extending Monads with Pattern Matching (Haskell 2011)http://tomasp.net/blog/docase-haskell.aspxWed, 20 Jul 2011 00:19:37 GMTThe blog post presents a paper that extends Haskell with pattern matching on monadic values. The paper has been accepted for publication at Haskell Symposium 2011 and extends the idea of joinads that I previously created for F#. The paper provides deeper theoretical background and discusses Haskell implementation.Tomas Petricek<p>Some time ago, I wrote a <a href="http://tomasp.net/blog/match-bang-paper.aspx">paper about <em>joinads</em></a> and the <code>match!</code> extension of the F# language. The paper was quite practically oriented and didn't go into much details about the theory behind <em>joinads</em>. Many of the examples from the F# version relied on some imperative features of F#. I believe that this is useful for parctical programming, but I also wanted to show that the same idea can work in the <em>purely functional</em> context.</p> <p>To show that joinads work in the pure setting, I created a Haskell version of the idea. The implementation (available below) is quite simple and consists of a pre-processor for Haskell source files and numerous examples. However, more important part of the recent work of joinads is a more detailed theoretical background.</p> <p>The theory of joinads, together with the language design of Haskell extension that implements it is discussed in a paper <em>Extending Monads with Pattern Matching</em>, which was accepted for publication at the <a href="http://www.haskell.org/haskell-symposium/2011/index.html">Haskell Symposium 2011</a>. Here is the abstract of the paper:</p> <p style="padding-left:60px;padding-right:60px;font-style:italic;"> Sequencing of effectful computations can be neatly captured using monads and elegantly written using <code>do</code> notation. In practice such monads often allow additional ways of composing computations, which have to be written explicitly using combinators. </p><p style="padding-left:60px;padding-right:60px;font-style:italic;"> We identify joinads, an abstract notion of computation that is stronger than monads and captures many such ad-hoc extensions. In particular, joinads are monads with three additional operations: one of type <code>m a -&gt; m b -&gt; m (a, b)</code> captures various forms of <em>parallel composition</em>, one of type <code>m a -&gt; m a -&gt; m a</code> that is inspired by <em>choice</em> and one of type <code>m a -&gt; m (m a)</code> that captures <em>aliasing</em> of computations. Algebraically, the first two operations form a near-semiring with commutative multiplication. </p><p style="padding-left:60px;padding-right:60px;font-style:italic;"> We introduce <code>docase</code> notation that can be viewed as a monadic version of <code>case</code>. Joinad laws make it possible to prove various syntactic equivalences of programs written using <code>docase</code> that are analogous to equivalences about <code>case</code>. Examples of joinads that benefit from the notation include speculative parallelism, waiting for a combination of user interface events, but also encoding of validation rules using the intersection of parsers. </p> <p>Links to the full paper, source code and additional materials are <a href="http://tomasp.net/blog/docase-haskell.aspx#dscl">available below</a>.</p>Fun with parallel monad comprehensions (The Monad.Reader)http://tomasp.net/blog/comprefun.aspxTue, 19 Jul 2011 23:28:29 GMTMonad comprehensions are back in Haskell, more powerful than ever before! The recent implementation adds expressive power by generalizing grouping, ordering and also parallel list comprehensions. This article shows how to use this new expressivity for programming with parsers and writing parallel and concurrent computations.Tomas Petricek<p style="font-style:italic;"> This article is a re-publication of an article that I wrote some time ago for <a href="http://themonadreader.wordpress.com/">The Monad.Reader</a> magazine, which is an online magazine about functional programming and Haskell. You can also read the article in the original PDF format as part of the <a href="http://themonadreader.files.wordpress.com/2011/07/issue18.pdf">Issue 18</a> (together with two other interesting articles). The samples from the article can be found <a href="https://github.com/tpetricek/Haskell.Joinads">on Github</a>. </p> <p>Monad comprehensions have an interesting history. They were the first syntactic extension for programming with monads. They were implemented in Haskell, but later replaced with plain list comprehensions and monadic <code>do</code> notation. Now, monad comprehensions are back in Haskell, more powerful than ever before!</p> <p>Redesigned monad comprehensions generalize the syntax for working with lists. Quite interestingly, they also generalize syntax for zipping, grouping and ordering of lists. This article shows how to use some of the new expressive power when working with well-known monads. You'll learn what "parallel composition" means for parsers, a poor man's concurrency monad and an evaluation order monad.</p> <ul> <li><a href="http://tomasp.net/blog/comprefun.aspx">Continue reading on the web...</a></li> <li><a href="http://themonadreader.files.wordpress.com/2011/07/issue18.pdf">Get The Monad.Reader Issue 18</a> (PDF)</li> </ul>Safer asynchronous workflows for GUI programminghttp://tomasp.net/blog/safe-gui-async.aspxWed, 15 Jun 2011 21:36:40 GMTWhen writing reactive applications using F# asynchronous workflows, it is important to run some operations on the right thread. User interface elements are accessible only on GUI threads and CPU-intensive computations should be done on a background thread. This article describes an extension of F# asynchronous workflows that guarantees correct use of threads using types.Tomas Petricek<img src="http://tomasp.net/articles/safe-gui-async/screen.png" style="float:right; margin:0px 0px 0px 15px;" /> <p>In the <a href="http://tomasp.net/blog/async-non-blocking-gui.aspx">previous article</a>, I discussed how to use F# asynchronous work­flows for creating reactive user-interfaces. One of the main concerns was to avoid blocking the GUI thread (to prevent the user-interface from freezing). The workflow shouldn't perform any CPU-intensive compu­tation when running on the GUI thread.</p> <p>The standard F# library provides two ways to run a computation on a background thread from an asynchronous workflow. The <code>StartChild</code> operation starts an operation in the thread pool and returns a workflow that can be called using asynchronous (non-blocking) <code>let!</code> construct. The <code>SwitchToThreadPool</code> operation can be called using <code>do!</code> and resumes the rest of the workflow on a background thread.</p> <p>When using the <code>SwitchToThreadPool</code> operation, we also need to eventually use <code>SwitchToContext</code> to transfer the execution back to the GUI thread (after completing the CPU-intensive calculations). In this article, I describe a variation of F# asynchronous workflows that keeps track of the running thread in the type of the computation. As a result, calling a workflow that should be executed on a GUI thread from a background thread is a compile-time error as opposed to failing at runtime.</p> Writing non-blocking user-interfaces in F#http://tomasp.net/blog/async-non-blocking-gui.aspxFri, 10 Jun 2011 23:36:16 GMTF# asynchronous workflows are mainly used for non-blocking I/O and concurrency, but they provide nice abstraction for writing user interface interactions. This article shows how to avoid blocking the user-interface when performing CPU-intensive processing.Tomas Petricek<img src="http://tomasp.net/articles/async-non-blocking-calls/screen.png" style="float:right; margin:0px 0px 0px 15px;" /> <p>F# asynchronous workflows are best known as a way to write efficient I/O operations or as an underlying mechanism of F# agent-based programming (using the <code>MailboxProcessor</code> type). However, they are also very useful for user-interface programming. I think this is a very interesting and important area, so I already wrote and talked about this topic - it is covered in <a href="http://manning.com/petricek/">Chapter 16 of my book</a> (there is a <a href="http://dotnetslackers.com/articles/net/Programming-user-interfaces-using-f-sharp-workflows.aspx">free excerpt</a>) and I <a href="http://tomasp.net/blog/reactive-talk.aspx">talked about it</a> at F#unctional Londoners meeting.</p> <p>Many applications combine user-interface programming (such as waiting for an event asynchronously) with some CPU-intensive tasks. This article looks at an example of such application and I'll explain how to avoid blocking the user-interface when doing the CPU-intensive task. The article starts with an example that is wrong and blocks the user-interface when doing data processing. Then I'll show you two options for fixing the problem. The three most important functions from the standard F# library that I'll discuss are <code>Async.StartChild</code> and <code>Async.SwitchTo­ThreadPool</code> with <code>Async.SwitchToContext</code>.</p> <p>This is the first article of a mini-series. In the next article, I'll demonstrate a simple wrapper for F# <code>async</code> that makes it more difficult to write <em>wrong</em> programs. The wrapper keeps the desired thread (GUI or background) in the type of the computations and code that would block the user interface will not type-check. But first, let's look at the example...</p> Explicit speculative parallelism for Haskell's Par monadhttp://tomasp.net/blog/speculative-par-monad.aspxTue, 17 May 2011 13:59:06 GMTThis article shows how to extend Haskell's Par monad to support cancellation of computations. This makes it possible to implement speculative parallelism using the monad and to build other high-level abstraction such as the unamb operator designed by Conal Elliott.Tomas Petricek<p>Haskell provides quite a few ways for writing parallel programs, but none of them is fully automatic. The programmer has to use some annotations or library to run computations in parallel <em>explicitly</em>. The most recent paper (and library) for writing parallel programs follows the latter approach. You can find more information about the library in a paper by Simon Marlow et al. <a type="external" href="http://research.microsoft.com/en-us/um/people/simonpj/papers/parallel/monad-par.pdf">A monad for deterministic parallelism</a> and it is also available on <a href="http://hackage.haskell.org/package/monad-par" type="external">Hackage</a>. However, I'll explain all the important bits that I'll use in this article.</p> <p>The library provides an explicit way for writing parallel programs using a <code>Par</code> monad. The library contains constructs for spawning computations and sharing state using blocking variables. However, the whole programming model is fully deterministic. I believe that it is sometimes useful to lift the determinacy requirement. Some programs are deterministic, but the fact cannot be (easily) automatically verified. For example, say you have two functions <code>fib1</code> and <code>fib2</code>. They both give the same result, but each of them is more efficient than the other one on certain inputs. To calculate a Fibonacci number, the program could <em>speculatively</em> try to evaluate both functions in parallel and return the result of the one that finishes first.</p> <p>Unfortunately, this cannot be safely implemented using a fully deterministic library. In this article, I'll show some examples where speculative parallelism can be useful and I'll talk about an extension to the <code>Par</code> monad that I implemented (available on <a href="https://github.com/tpetricek/Haskell.ParMonad">GitHub</a>). The extension allows programmers to write <em>speculative computations</em>, provided that they manually verify that their code is deterministic. </p> Variations in F#: Research compiler with Joinads and more!http://tomasp.net/blog/fsharp-variations-joinads.aspxFri, 25 Mar 2011 00:04:08 GMTJoinads are a research extension of the F# language. They simplify conrurrent programming with tasks, reactive programming with events, but can be also used for other types of computations. This article introduces the extension, which is now available, based on the open-source source-drop of F#.Tomas Petricek<p>In this article, I'll write about an experimental extension for F# that I call <em>joinads</em>. If you're following my blog, you may have seen an <a href="http://tomasp.net/blog/match-bang-paper.aspx">academic paper</a> that I wrote about it some time ago. Anyway, the motivation for the extension is that there are many useful programming models for reactive, concurrent and parallel programming that would deserve some syntactic support in the programming language.</p> <p>For example, when programming with <em>futures</em> (the <code>Task&lt;T&gt;</code> type), you may want to implement logical "or" operator for tasks that returns <code>true</code> immediately when the first task completes returning <code>true</code>. When programming with <em>events</em> (the <code>IObservable&lt;T&gt;</code> type), we'd like to wait for the event that happens first. Finally, when programming using <em>agents</em>, we sometimes need to wait only for certain types of messages. All of these problems can be solved, but require the use of (sometimes fairly complicated) functions. Joinads make it possible to solve them directly using the <code>match!</code> syntax. For example, here is the "or" operator for tasks:</p> <pre class="fssnip"> <span class="l">1: </span><span onmouseout="hideTip(event, 'jofs1', 1)" onmouseover="showTip(event, 'jofs1', 1)" class="i">future</span> { <span class="l">2: </span> <span class="k">match!</span> <span onmouseout="hideTip(event, 'jofs2', 2)" onmouseover="showTip(event, 'jofs2', 2)" class="i">after</span> <span class="n">100</span> <span class="k">true</span>, <span onmouseout="hideTip(event, 'jofs2', 3)" onmouseover="showTip(event, 'jofs2', 3)" class="i">after</span> <span class="n">1000</span> <span class="k">false</span> <span class="k">with</span> <span class="l">3: </span> | <span class="o">!</span><span class="k">true</span>, _ <span class="k">-&gt;</span> <span class="k">return</span> <span class="k">true</span> <span class="l">4: </span> | _, <span class="o">!</span><span class="k">true</span> <span class="k">-&gt;</span> <span class="k">return</span> <span class="k">true</span> <span class="l">5: </span> | <span class="o">!</span><span onmouseout="hideTip(event, 'jofs3', 4)" onmouseover="showTip(event, 'jofs3', 4)" class="i">a</span>, <span class="o">!</span><span onmouseout="hideTip(event, 'jofs4', 5)" onmouseover="showTip(event, 'jofs4', 5)" class="i">b</span> <span class="k">-&gt;</span> <span class="k">return</span> <span onmouseout="hideTip(event, 'jofs3', 6)" onmouseover="showTip(event, 'jofs3', 6)" class="i">a</span> <span class="o">||</span> <span onmouseout="hideTip(event, 'jofs4', 7)" onmouseover="showTip(event, 'jofs4', 7)" class="i">b</span> }</pre> <p>I'll write more about this example (and the implementation) in a later article. This article focuses on the compiler extension itself. I created a first implementation of the idea above during my <a href="http://tomasp.net/blog/internship-match-bang.aspx">internship with Don Syme at MSR Cambridge</a>, but then changed it quite a bit when writing the academic paper mentioned above. However, I never released the source code. </p> <p>Thanks to the <a href="http://blogs.msdn.com/b/dsyme/archive/2010/11/04/announcing-the-f-compiler-library-source-code-drop.aspx">open-source release of F#</a> it is now quite easy to modify the F# compiler and make the modifications available, so I decided I should finally release my F# extensions. I also recently <a href="http://tomasp.net/blog/idioms-in-linq.aspx">blogged</a> <a href="http://tomasp.net/blog/formlets-in-linq.aspx">about</a> encoding <em>idioms</em> (also called <em>applicative functors</em>) in C#. I was wondering how to do that in F# and so I also created a simple extension computations based on this abstraction. The support for <em>idioms</em> is just an experiment, but it could be useful, for example, for programming with formlets. You'll find more about it at the end of the article. </p> <p>You can find the <a href="https://github.com/tpetricek/FSharp.Extensions">source code on my GitHub</a> (there is also a link compiled binaries at the end of the article). The source code is cloned from an F# Mono repository, which means that it should build on Linux and MacOS too. </p> <div class="tip" id="jofs1">val future : FutureBuilder<br /><br />Full name: JoinadsDemo.future<br /></div> <div class="tip" id="jofs2">val after : int -&gt; 'a -&gt; Task&lt;'a&gt;<br /><br />Full name: JoinadsDemo.after<br /></div> <div class="tip" id="jofs3">val a : bool<br /><br />  type: bool<br />  implements: IComparable<br />  implements: IConvertible<br />  implements: IComparable&lt;bool&gt;<br />  implements: IEquatable&lt;bool&gt;<br />  inherits: ValueType<br /></div> <div class="tip" id="jofs4">val b : bool<br /><br />  type: bool<br />  implements: IComparable<br />  implements: IConvertible<br />  implements: IComparable&lt;bool&gt;<br />  implements: IEquatable&lt;bool&gt;<br />  inherits: ValueType<br /></div> Beyond the Monad fashion (II.): Creating web forms with LINQhttp://tomasp.net/blog/formlets-in-linq.aspxMon, 14 Mar 2011 17:14:49 GMTFormlets are elegant functional abstraction for describing web forms encapsulating both rendering and functionality. In this article, we look how to write formlets in C#. Although formlets are not monads, we can still use elegant LINQ syntax. Interestingly, using the join clause...Tomas Petricek<img src="http://tomasp.net/articles/formlets-in-linq/screen.png" style="margin:15px;float:right;" /> <p>The LINQ query syntax can be used for various things. Aside from writing queries, you can also use it to encode any <em>monads</em>. This has become a fashionable topic, so you can learn more about it at many .NET conferences (for example <a href="http://gotocon.com/cph-2011/tracks/show_track.jsp?trackOID=434">GOTO 2011</a>). There are also many blog posts on this topic and I explained it in details in Chapter 12 of <a href="http://manning.com/petricek">my book</a>, which is available as a <a href="http://manning.com/petricek/SampleChapter12.pdf">free sample chapter</a> (PDF).</p> <p>However, you can also use LINQ syntax for writing different types of computations. In a <a href="http://tomasp.net/blog/idioms-in-linq.aspx">previous blog post</a>, I introduced <em>idioms</em> (also called <em>applicative functors</em>) and I demonstrated how to use the <code>join</code> syntax in LINQ to write computations based on idioms. We looked at a slightly boring, but simple example - zipping of lists - and we also implemented matrix transposition.</p> <p>In this blog post, we look at a more exciting example. I explain <em>formlets</em>, which is an <em>idiom</em> for building web forms. Formlets give us an elegant functional way to create reusable components that encapsulate both visual aspect (HTML) and behavior (processing of requests). You can think of them as functional ASP.NET controls. Formlets come from the <a href="http://groups.inf.ed.ac.uk/links/formlets/">Links project</a> and they are now used in commercial products like <a href="http://www.websharper.com/tutorials/GettingStartedWithFormlets.aspx">WebSharper</a>. In this article, you'll see that we can (mis)use LINQ to get a nicer syntax for writing code using formlets. My C# implementation of formlets is based on a nice <a href="http://bugsquash.blogspot.com/2011/01/simple-implementation-of-formlets-in-f.html">F# formlets by Mauricio Scheffer</a>.</p> Beyond the Monad fashion (I.): Writing idioms in LINQhttp://tomasp.net/blog/idioms-in-linq.aspxThu, 10 Mar 2011 13:26:00 GMTEveryone tells you that LINQ is a <em>monad</em>, but LINQ can be used to enocde other types of computations too. This article demonstrates that you can use LINQ to program using <em>idioms</em>, which are in some ways more useful than monads.Tomas Petricek<p>Thanks to LINQ and Erik Meier, monads have become a fashionable topic in the C# developer community. Indeed, no serious developer conference on .NET can get away without having a talk on monads. The attractive thing about LINQ and monads is that the <code>SelectMany</code> operator roughly corresponds to the <em>bind</em> function that defines a monad. In practice, LINQ is used for working with collections of data (<code>IEnumerable&lt;T&gt;</code>), but you can also define <em>bind</em> (i.e. <code>SelectMany</code>) for some other data types and use the LINQ syntax for working with other types. You won't be really using the full LINQ syntax. You'll probably use just nested <code>from</code> clauses (for <em>binding</em>) and <code>select</code> at the end to return the result.</p> <p>However, monads are not the only notion of computation that we can work with. More interestingly, they are also not the only notion of computation that you can encode using LINQ! In this article, I'll briefly introduce <em>idioms</em> (also called <em>applicative functors</em>), which is another useful abstract type of computations. Idioms can be used for a few things that cannot be done using monads.</p> <p>A provocative summary of this article is: <span style="font-variant:small-caps">"Everyone who tells you that LINQ is a monad is wrong!"</span></p> <p>The truth is that LINQ syntax can be used for encoding <em>queries</em> (obviously), <em>monads</em> (as you were told), but also for <em>idioms</em> as you'll learn today (and quite possibly for other types of computations). In this article, we look at a basic example, but I'll describe a more complex real-world scenario in the next blog post.</p> Reactive, parallel and concurrent programming in F# (PADL 2011)http://tomasp.net/blog/match-bang-paper.aspxMon, 25 Oct 2010 00:00:37 GMTAn academic paper that presents an extension for F# computation expressions, which can be used for encoding a wide range of reactive, parallel and concurrent programming models in a simple way in F#.Tomas Petricek<p>Don Syme blogged about <a href="http://blogs.msdn.com/b/dsyme/archive/2010/10/21/the-f-asynchronous-programming-model-padl-2010-pre-publication-draft.aspx" type="extenal"> a paper on the F# Asynchrounous Programming Model</a> that I helped to write. Without any doubt, the asynchronous programming features of F# are one of the reason for its success and also influence other teams in Microsoft. However, I'm very glad that there is now also an academic paper that makes this idea accessible to the academic community. I believe that the ideas could evolve in interesting ways when used in other programming languages and also, it is now easier to create research projects that build on top of the F# model.</p> <p>Don already mentioned that we have another paper accepted at PADL. The paper describes work that started during my internship at Microsoft Research in 2009. It presents a simple language extension for <em>computation expressions</em> that makes them even more useful in some reactive, concurrent and parallel programming models. Note that this is only a research project and there are currently no plans to support the extension in the F# language (although, if there will, eventually, be an open-source F# release, then you'll hear about the extension again...)</p> <p>Here is the abstract of the paper (accepted at <a href="http://www.dcc.fc.up.pt/PADL-2011/">PADL 2011</a>) and a PDF download link:</p> <h3 style="padding-left:60px;padding-right:60px;">Joinads: A retargetable control-flow construct for reactive, parallel and concurrent programming</h3> <p style="padding-left:60px;padding-right:60px;font-style:italic;"> Modern challenges led to a design of a wide range of programming models for reactive, parallel and concurrent programming, but these are often difficult to encode in general purpose languages. We present an abstract type of computations called joinads together with a syntactic language extension that aims to make it easier to use joinads in modern functional languages. </p> <p style="padding-left:60px;padding-right:60px;font-style:italic;"> Our extension generalizes pattern matching to work on abstract computations. It keeps a familiar syntax and semantics of pattern matching making it easy to reason about code, even in a non-standard programming model. We demonstrate our extension using three important programming models – a reactive model based on events; a concurrent model based on join calculus and a parallel model using futures. All three models are implemented as libraries that benefit from our syntactic extension. This makes them easier to use and also opens space for exploring new useful programming models.</p> <ul> <li>Download the <a href="http://tomasp.net/academic/joinads/joinads.pdf">full text</a> (PDF, pre-publication draft)</li> </ul> <p>The paper can still be revised before the final publication, so any comments and suggestions for improvement are largely welcome. You can contact me either via comments (below) or using email at <a href="mailto:tomas@tomasp.net">tomas@tomasp.net</a>. I would be also quite interested to hear from anybody who would like to implement similar feature in other programming languages (for example Haskell or Scala).</p> The Duality of Object and Event referenceshttp://tomasp.net/blog/event-object-duality.aspxMon, 19 Jul 2010 16:58:05 GMTThis article describes an interesting example of mathematical duality in programming languages - the duality between references between objects and references between events. The idea is useful for understading what events are garbage and can be garbage collected.Tomas Petricek<p>Mathematical duality [<a href="http://tomasp.net/blog/event-object-duality.aspx&#xD;&#xA;#duallinks">2</a>] is a very useful and elegant concept that gives us a nice way of speaking about objects or structures that behave in some way exactly conversely. There is no clear definition of what <em>duality</em> is. However, the idea is that when we have two structures that behave conversely and we know that something is true about the first one, then we get the opposite statement about the other structure "for free" (if you know how to translate from one structure to the other).</p> <p>In this article, I'll talk about an interesting example of duality that (to my best knowledge) wasn't described by anyone before. The two dual structures are <strong>references between objects</strong> in a normal program and <strong>references between events</strong> in a reactive application. The statement that is going to become obvious thanks to the duality principle is describing which of the objects (or events) are garbage and can be safely collected by garbage collector.</p> <p>This topic is in much more details discussed in a paper [<a href="http://tomasp.net/blog/event-object-duality.aspx&#xD;&#xA;#duallinks">4</a>] I wrote with <a href="http://research.microsoft.com/en-us/people/dsyme/">Don Syme</a> and that I presented at the ISMM Workshop (see also <a href="http://tomasp.net/blog/pldi-2010-trip.aspx">my trip report from PLDI</a>). In this article, I'll try to give an accessible description of the most interesting idea from the paper...</p>