Blog | TomasP.Net, Tomas PetricekBlog The RSS feed has been moved 26 Aug 2013 20:54:46 GMT The new feed is available at <a href=""> </a> Power of mathematics: Reasoning about functional types, 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="" 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="">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> Async in C# and F#: Asynchronous gotchas in C#, 15 Apr 2013 04:00:03 GMTThis article is inspired by an MVP summit talk about common pitfalls in the C# asynchronous programming model. I look at a number of easy to make mistakes when writing asynchronous code in C# and demonstrate that most of them would not easily happen when using F#.Tomas Petricek<p>Back in February, I attended the annual MVP summit - an <a href="">event organized by Microsoft for MVPs</a>. I used that opportunity to also visit Boston and New York and do two F# talks and to record a <a href="" title="Tomas Petricek (Channel 9): How F# Learned to Stop Worrying and Love the Data">Channel9 lecutre about type providers</a> [<a href="#rf13041502">5</a>]. Despite all the <em>other activities</em> (often involving pubs, other F# people and long sleeping in the mornings), I also managed to come to some talks!</p> <div style="margin-left:auto;margin-right:auto;width:379px;margin-top:10px;margin-bottom:20px;"> <img src="" style="width:379px;" /> </div> <p>One (non-NDA) talk was the <a href="" title="Lucian Wischik, Stephen Toub: Async Clinic">Async Clinic</a> [<a href="#rf13041502">1</a>] talk about the new <code>async</code> and <code>await</code> keywords in C# 5.0. Lucian and Stephen talked about common problems that C# developers face when writing asynchronous programs. In this blog post, I'll look at some of the problems from the F# perspective. The talk was quite lively, and someone recorded the reaction of the F# part of the audience as follows...</p> F# Data: New type provider library, 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="" 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="">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="">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="">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="">F# Data source code on GitHub</a></li> <li><a href="">F# Data documentation &amp; tutorials</a></li> <li><a href="">F# Data on NuGet</a></li> </ul> <p>Before looking at the details, I would like to thank to <a href="">Gustavo Guerra</a> who made some amazing contributions to the library! (More contributors are always welcome, so continue reading if you're interested...)</p> Upcoming F# talks and trainings (London, NYC &amp; Boston), 07 Feb 2013 23:00:22 GMTAfter a few years, I will be attending the MVP summit again this year. The good news for those interested in F# is that I have two talks scheduled along the way in New York and Boston. Aside from that, we also have dates for a new F# course in London and New Year!Tomas Petricek<img src="" class="rdecor" title="Tomas Petricek" style="margin:10px 35px 15px 35px;width:100px" /> <p>After a few years, I finally managed to find the time to attend the <a href="">MVP Summit</a> this year. The Summit is an annual event where people who are active in Microsoft technical communities come to the Microsoft headquarters to learn about new things (and, of course, tell them how they should be doing their job :-)). The Summit is a great place to meet interesting people (so if you're reading this and will be there, definitely get in touch!) </p> <p>The good news - for those interested in F# - is that I'll be doing two F# talks on the way and we also have a new F# course scheduled for later in the year. <a href="">Continue reading to learn more!</a></p>Announcing: Literate programming tools for F#, 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="" 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="">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="">F# Formatting home page</a></li> <li><a href="">F# Formatting source code</a> on GitHub</li> <li><a href="">F# Formatting package</a> on NuGet</li> </ul> <p>To learn more about the tool and how to use it, <a href="">continue reading!</a></p>Processing trees with F# zipper computation, 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:</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> Manning: F# Deep Dives deal of the day, 18 Dec 2012 17:19:57 GMTThere is an increasing number of commercial F# uses. If you want to learn about the domains where F# is used (including finance, game development, machine learning and other) as well as about common programming techniques in F#, then the upcoming <strong>F# Deep Dives</strong> book is the book for you!Tomas Petricek<img src="" class="rdecor" title="F# Deep Dives" style="margin-bottom:15px" /> <p> The F# language has been around for longer than many people suspect. My <a href="">first, completely outdated, blog post</a> was from May 2006. The Microsoft Research releases, sometime around 2006 were the first stable versions that gained some interest and slowly attracted commercial users. </p> <p>A lot has changed since the early days. F# now includes powerful features like <em>computation expressions</em> and <em>asynchronous workflows</em> and F# 3.0 comes with unique <em>type provider</em> mechanism. </p> <p>There is an increasing number of users from diverse domains: F# is used to model complex domains in <a href="">finance</a> and science; asynchronous and concurrent features are used to write server-side components of <a href="">social games</a> and <a href="">trading systems</a>, but also in <a href="">web programming</a>; the expressivity of F# is used by machine learning experts to handle dirty data or <a href="">classify XBox players</a>. Moreover, the <a href="">F# Software Foundation</a> has been recently founded to support the collaboration between different commercial users, open-source community and academia. </p> <p>There is an increasing interest in F#, but many of those who approach it ask (excellent) questions such as: <em>"In what problem domains can I benefit from F#?"</em> or <em>"How do I use F# in finance/science/gaming or web programming?"</em> and most importantly <em>"How do I approach different problems in F#?"</em> </p>Learn F# at TechMesh and SkillsMetter, 21 Oct 2012 16:53:04 GMTLooking for an event where you could learn about F#? The second half of autumn will be a busy time with Progressive F# Tutorials happening at the beginning of November and the TechMesh Conference planned for the first week in December!Tomas Petricek<img src="" class="rdecor" title="Tomas Petricek" style="margin-bottom:15px" /> <p>Autumn is a busy period and I already invited you to a <a href="">couple of interesting events</a>, but there are two more events that you definitely should not miss. In only two weeks, you can come to two-day <a href="">Progressive F# Tutorials</a> packed with tutorials for both F# beginners and experts. At the beginning of December, the <a href="">TechMesh Conference</a> comes with three days of talks about alternative (and future) technologies. </p> <p>I'll be speaking at both Progressive F# Tutorials and TechMesh and I'm also doing a tutorial at TechMesh, so if you want to learn about F#, type providers in F# 3.0 and financial computing with F#, here are some talks that you should not miss... </p> Applicative functors: definition and syntax, 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="" 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="" 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="" 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="" 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 matters, 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="" 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="">teaching it at our F# trainings</a> for the last year)...</p>F# Courses and Talks for Autumn 2012 (I.), 08 Aug 2012 03:47:08 GMTThis article is an invitation to a number of F# events at the end of summer and during autumn. Aside from F# trainings in New York and London, I will be also doing an F# tutorial at CUFP in Copenhagen.Tomas Petricek<img src="" class="rdecor" title="Tomas Petricek" style="margin-bottom:15px" /> <p>Similarly to the <a href="">last year</a>, I already have a number of F# events planned for the end of the summer and autumn that I'd like to invite you to!</p> <p>The <a href="">Visual Studio 2012 has been completed</a> recently and it comes with F# 3.0. For me, this means two things. Firstly, it is the second Visual Studio version of F#, which means that functional programming is worth taking seriously. Secondly, F# 3.0 comes with <em>type providers</em>, which is a killer feature for working with data. No matter if you're a C# programmer now to functional programming or if you're an F# user in the real-world, I hope you can find some interesting and useful event below! </p> <p>The two main things that I'm going to be involved in are SkilsMatter trainings in London and New York and a few events at the biggest functional conference (ICFP) in Copenhagen...</p> The theory behind covariance and contravariance in C# 4, 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="" 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> Reporting events from F# Agents, 16 Jun 2012 00:23:35 GMTThis article describes different options for reporting events from F# agents. The options include triggering the event directly, using thread pool and in a specified context.Tomas Petricek<p>Over the last year, I wrote quite a lot of articles about agent-based programming in F#. Agents (inspired by Erlang) provide a great abstraction for writing concurrent and scalable systems. They are a great fit for both server-side development (for example, handling a large number of concurrent requests), but also for user interface (for example, keeping state in an application with background tasks and interactive interface).</p> <p>When writing reusable agents, we usually encapsulate agent in an F# object type. The type provides methods for sending messages to the agent. However, sometimes the agent also needs to report some state change that can be handled by another interested agent. This is done using F# events. However, F# events do not specify threading behaviour, so there is a number of options.</p> <p>In this article (inspired by a recent email discussion), I describe three ways of reporting events from an agent. The options differ in what thread is used to report the event. Choosing the right option is important as it affects scalability and simplicity of your agent-based code.</p> F# in Academia: Present at upcoming events!, 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 language 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="">Continue reading!</a></p>TryJoinads (VII.) - Implementing joinads for async workflows, 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="">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="">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=""></a> web page. If you read the article there, you can run the examples interactively and experiment with them: <a href="">view the article on TryJoinads</a>.</em></p> TryJoinads (VI.) - Parsing with joinads, 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=""></a> web page. If you read the article there, you can run the examples interactively and experiment with them: <a href="">view the article on TryJoinads</a>.</em></p> Asynchronous client/server in F# (QCon 2012), 12 Mar 2012 01:09:02 GMTLast week, I gave a talk on asynchronous programming in F# at QCon London. I used the one hour slot to implement a Social Rectangle Drawing App - an application that showed the importance of asynchronous workflows on both client-side and server-side.Tomas Petricek<img src="" alt="Qcon" class="rdecor" /> <p>Last week, I gave a talk on asynchronous programming in F# at <a href="">London QCon 2012</a>. The talk was a part of <a href="">The Rise of Scala &amp; Functional Programming</a> track organized by Charles Humble. Reactive and asynchronous programming was a topic that was repeated a couple of times during the whole session - Sadek Drobi talked about <a href=",%20composable%20reactive%20web%20programming%20with%20Iteratees%20in%20Play2">non-blocking reactive web framework Play2</a> and Damien Katz talked about <a href="">Erlang and CouchDB</a>.</p> <p>I used the one hour slot to implement "Rectangle Drawing App" - a simple application that shows how to write complete client-server application just using F#. On the server-side, I used asynchronous workflows to write HTTP server with an F# agent. On the client-side, I used asynchronous workflows to express user interface logic and the <a href="">Pit project</a> to run F# code as JavaScript that works everywhere. The app definitely had a huge commercial potential:</p> <div style="text-align:center"> <img src="" alt="Quote" /> </div> TryJoinads (V.) - Implementing the option joinad, 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="">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=""></a> web page. If you read the article there, you can run the examples interactively and experiment with them: <a href="">view the article on TryJoinads</a>.</em></p> TryJoinads (IV.) - Concurrency using join calculus, 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=""></a> web page. If you read the article there, you can run the examples interactively and experiment with them: <a href="">view the article on TryJoinads</a>.</em></p> TryJoinads (III.): Agent-based programming, 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=""></a> web page. If you read the article there, you can run the examples interactively and experiment with them: <a href="">view the article on TryJoinads</a>.</em></p> TryJoinads (II.): Task-based parallelism, 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=""></a> web page. If you read the article there, you can run the examples interactively and experiment with them: <a href="">view the article on TryJoinads</a>.</em></p> TryJoinads (I.) - Asynchronous programming, 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=""></a> web page. If you read the article there, you can run the examples interactively and experiment with them: <a href="">view the article on TryJoinads</a>.</em></p> Introducing TryJoinads.org, 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 where you can experiment with the extension using a web-based F# console.Tomas Petricek<div class="rdecor" style="text-align:center"> <a href="" target="_blank"> <img src="" alt="TryJoinads.Org web site" style="border:none" /> </a><br /> <small>(<a href="" 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="">PADL 2011</a> and <a href="">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>F# courses and talks (Winter 2012 and beyond...), 13 Jan 2012 03:07:13 GMTA couple of months ago, I posted a list of my F# talks and courses for Autumn 2011. Although I tried hard to have fewer speaking engagements during the winter and spring, there are quite a few events thatTomas Petricek<img src="" class="rdecor" title="I'm not singing at an opera! That's a photo from a normal F# talk..." style="margin-bottom:15px" /> <p>A couple of months ago, I posted a list of my <a href=""> F# talks and courses for Autumn 2011</a>. Although I tried hard to have <em>fewer</em> speaking engagements during the winter and spring, there are quite a few events that I'd like to invite you to. </p> <p>Last year, I spent quite a lot of time talking about asynchronous programming and agents. I think this is still a very important topic and especially agent-based programming in F# is a powerful way to implement concurrency primitives (like blocking queue), as well as complex systems (like <a href="">trading screens</a> and <a href="">market analysis</a>). I also wrote a series of articles on this topic that <a href="">are available on MSDN</a> and should be a good starting point.</p> <p>Over the next few months, I'll be doing some talks about type providers, which is an upcoming F# 3.0 technology for accessing data. However, I also hope to find some time to look at other directions for F#, especially how it can be used in an online web-based environment, either using Azure or by translating F# to JavaScript using a recently announced <a href="">open-source project named Pit</a>.</p> <p><a href="">Continue reading</a> to see the list of planned talks, tutorials and courses....</p>Regions and navigation bar for F# in Visual Studio, 01 Jan 2012 23:02:47 GMTThe beginning of a new year may be a good time for writing one lightweight blog post - this article shows two hidden features of F# IntelliSense in Visual Studio and also talks about writing plugins using the F# open-source release.Tomas Petricek<p>The beginning of a new year may be a good time for writing one lightweight blog post that I wanted to publish for some time now. During my last internship with the F# team at MSR, I did some work on improving the F# IntelliSense in Visual Studio. This mostly involved the usual features - automatic completion, colouring and tooltips. The F# IntelliSense in Visual Studio 2010 still isn't perfect, but I think it is safe to claim that it is the best IDE experience for a typed functional programming language (aside, you can vote for some F# IDE features <a href="">here</a> and <a href="">here</a>). </p> <div style="text-align:center"> <img src="" title="F# with regions and navigation bar in Visual Studio" style="margin-bottom:5px;border-style:none" /> </div> F# Math (IV.) - Writing generic numeric code, 27 Nov 2011 17:19:32 GMTWriting generic numeric code in .NET is difficult, because .NET generics do not support constraints specifying that a type has to support certain numeric operations. In this article, we look how to solve the problem in F#. Using static member constraints, it is possible to write simple generic calculations and using the INumeric interface, we can capture numeric operations for a type and use them when implementing complex types such as a matrix.Tomas Petricek<p>Generic numeric code is some calculation that can be used for working with multiple different numeric types including types such as <code>int</code>, <code>decimal</code> and <code>float</code> or even our own numeric types (such as the type for <a href="">clock arithmetic from the previous article of the series</a>). Generic numeric code differs from ordinary generic F# code such as the <code>'a list</code> type or <code></code> function, because <em>numeric code</em> uses numeric operators such as <code>+</code> or <code>&gt;=</code> that are defined differently for each numeric type.</p> <p>When writing simple generic code that has some type parameter <code>'T</code>, we don’t know anything about the type parameter and there is no way to restrict it to a numeric type that provides all the operators that we may need to use in our code. This is a limitation of the .NET runtime and F# provides two ways for overcoming it.</p> <ul class="spaces"> <li><strong>Static member constraints</strong> can be used to write generic code where the actual numeric operations are resolved at compile-time (and a generic function is specialized for all required numeric types). This approach makes resulting code very efficient and is generally very easy to use when writing a function such as <code>List.sum</code>.</li> <li><strong>Global numeric associations</strong> (available in F# PowerPack) give us a way to obtain an interface implementing required numeric operations dynamically at runtime. This approach has some runtime overhead, but can be used for complex numeric types (such as <code>Matrix&lt;'T&gt;</code>).</li> <li><strong>Combination of both</strong> techniques can be used to implement complex numeric type that is generic over the contained numeric values and has only a minimal runtime overhead.</li> </ul> <p>Static member constraints are a unique feature of F# that is not available in other .NET languages, so if you're interested in writing numeric code for .NET, this may be a good reason for choosing F#. In C# or Visual Basic, you would be limited to the second option (which can be implemented in C#). In dynamic languages (like IronPython), everything is dynamic, so numeric computations can work with any numeric type, but will be significantly less efficient. In the rest of the article, we look at the three options summarized above. </p> <p style="font-style:italic;">This article is a part of a series that covers some F# and F# PowerPack features for numerical computing. Other articles in this series discuss matrices, defining custom numeric types and writing generic code. For links to other parts, see <a href="">F# Math - Overview of F# PowerPack</a>.</p> F# Math (III.) - Defining custom numeric types, 24 Nov 2011 19:21:35 GMTIn this article, we look at defining custom numeric types in F#. We'll create a numeric type representing numbers in a clock artihmetic (with base 5) and we'll see how to define custom operators, numeric literals and how to support F# PowerPack matrices.Tomas Petricek<p>In this article, we define an F# numeric type for calculating in the modular arithmetic (also called clock arithmetic) [<a href="#ppcnuml">1</a>]. Modular arithmetic is used for calculations where we want to keep a value within a specified range by counting in cycles. For example, a maximal value on clock is 12 hours. When we add 11 hours and 3 hours, the value overflows and the result is 2 hours. Aside from clocks, this numeric system is also essential in cryptography or, for example, in music.</p> <p>This tutorial shows several techniques that are essential when defining any new numeric type in F#. Most importantly, you’ll learn how to:</p> <ul> <li>Define a numeric type with overloaded operators </li> <li>Define a numeric literal for constructing numbers of our new type</li> <li>Enable calculating with our type in F# lists and matrices</li> <li>Hide implementation details of a numeric type</li> </ul> <p>We define type <code>IntegerZ5</code> that implements modular arithmetic with modulus 5, meaning that valid values are in the range from 0 to 4 and we equip the type with operations such as addition and multiplication. When an operation produces a value that would be outside of the range, we adjust it by adding or subtracting the modulus (in our case 5). Here are some examples of calculations that we’ll be able to write:</p> <pre> 2 + 1 = 3 (mod 5) 4 * 2 = 3 (mod 5) List.sum [ 0; 1; 2; 3 ] = 1 (mod 5) </pre> <p>In the first case, we can perform the operation without any adjustments. In the second case, we multiply 4 by 2 and get 8 as the result, which is out of the required range. To correct it, we calculate the remainder after a division by 5 (written as <code>8 % 5</code> in F#), which gives us 3. Finally, the last example shows that we’d also like to be able to use our type with lists. If we add values 0, 1, 2 and 3, we get 6 which is adjusted to 1.</p> <p style="font-style:italic;">This article is a part of a series that covers some F# and F# PowerPack features for numerical computing. Other articles in this series discuss matrices, defining custom numeric types and writing generic code. For links to other parts, see <a href="">F# Math - Overview of F# PowerPack</a>.</p> F# Math (II.) - Using matrices for graph algorithms, 09 Nov 2011 01:46:12 GMTThis article introduces the matrix type available in F# PowerPack. It discusses how to create matrices, manipulate matrices using indexing and slices and how to use built-in functions for working with them. As a running example, we use matrix to represent a graph using an adjacency matrix.Tomas Petricek <p>In the <a href="">previous article of this series</a>, we looked at <code>complex</code> and <code>BigRational</code>, which are two numeric types that are available in F# PowerPack. Aside from these two, the PowerPack library also contains a type <code>matrix</code> representing a two-dimensional matrix of floating-point values.</p> <p>In this article, you'll learn how to work with matrices in F#, using some of the functions provided by F# PowerPack. I'll demonstrate the library using an example that represents <em>graphs</em> using a, so called, <em>adjacency matrix</em>. If you're not familiar with this concept, you don't need to worry. It is quite simple and it will be clear once we look at an example. The matrix represents which vertices of a graph are connected with other vertices by an edge. Many of the standard operations on matrices are useful when working with adjacency matrix, so this tutorial will cover the following:</p> <ul> <li>Creating matrices from lists and using functions from the <code>Matrix</code> module</li> <li>Using slices to read or modify a part of matrix</li> <li>Performing standard operations with matrices such as transposition and matrix multiplication</li> <li>Using higher order functions for working with matrices</li> </ul> <p style="font-style:italic;">This article is a part of a series that covers some F# and F# PowerPack features for numerical computing. Other articles in this series discuss matrices, defining custom numeric types and writing generic code. For links to other parts, see <a href="">F# Math - Overview of F# PowerPack</a>.</p> F# Math (I.) - Numeric types in PowerPack, 02 Nov 2011 02:34:07 GMTThis article discusses two numeric types that are available in F# PowerPack - BigRational represents arbitrary precision rational numbers and complex represents (floating-point) complex numbers. The types can be nicely used from F# as well as from C#.Tomas Petricek<p>In this article, we'll briefly look at two numeric types that are available in F# PowerPack. The type <code>complex</code> represents complex numbers consisting of real and imaginary parts. Both parts are stored as a floating point numbers. The type <code>BigRational</code> represents rational numbers consisting of numerator and denominator of arbitrary sizes. Integers of arbitrary size are represented using <code>BigInteger</code> type that is available in .NET 4.0 (in the <code>System.Numerics.dll</code> assembly). On .NET 2.0, the <code>BigInteger</code> type is also a part of F# PowerPack.</p> <p style="font-style:italic;">This article is a part of a series that covers some F# and F# PowerPack features for numerical computing. Other articles in this series discuss matrices, defining custom numeric types and writing generic code. For links to other parts, see <a href="">F# Math - Overview of F# PowerPack</a>.</p> F# Math - Numerical computing and F# PowerPack, 02 Nov 2011 02:30:26 GMTThis article is the first article of a series where I'll explain some of the F# features that are useful for numeric computing as well as some functionality from the F# PowerPack library.Tomas Petricek<img src="" style="float:right;margin:0px 0px 5px 15px" /> <p>This article is the first article of a series where I'll explain some of the F# features that are useful for numeric computing as well as some functionality from the F# PowerPack library. Most of the content was originally written for the <a href="">Numerical Computing in F#</a> chapter on MSDN (that I <a href="">announced earlier</a>), but then we decided to focus on using F# with third party libraries that provide more efficient implementation and richer set of standard numeric functionality that's needed when implementing machine learning and probabilistic algorithms or performing statistical analysis. If you're interested in these topics, then the last section (below) gives links to the important MSDN articles.</p> <p>However, F# PowerPack still contains some useful functionality. It includes two additional numeric types and an implementation of matrix that integrates nicely with F#. The series also demonstrates how to use features of the F# language (and core libraries) to write numeric code elegantly. In particular, we'll use the following aspects:</p> <ul class="spaces"> <li><strong>Overloaded operators.</strong> Any type can provide overloaded version of standard numeric operators such as +, -, * and / as well as other non-standard operators (such as .*). As a result, libraries can implement their own numeric types which are indistinguishable from built-in types such as int.</li> <li><strong>Numeric literals.</strong> F# math libraries can enable using new numeric literals in the code. For example, you can write a <code>BigRational</code> value representing one third as <code>1N/3N</code>. The <code>N</code> suffix used in the notation is not hardcoded in the F# language and we'll see how to define similar numeric type.</li> <li><strong>Static constraints.</strong> F# supports static member constraints, which can be used for writing functions that work with any numeric type. For example, the <code>List.sum</code> function uses this feature. It can sum elements of any list containing numbers.</li> </ul> <p> These are just a few of the F# language features that are useful when writing numeric code, but there are many others. The usual F# development style using interactive tools, type safety that prevents common errors, units of measure as well the expressivity of F# make it a great tool for writing numeric code. For more information, take a look at the MSDN overview article <a href="">Writing Succinct and Correct Numerical Computations with F#</a>. </p> F# courses and talks (Autumn 2011), 26 Aug 2011 03:04:11 GMTAfter a quiet summer season, it is time to look at the upcoming F# talks and courses. If you want to learn about functional and asynchronous programming, F# and more, you may want to come to our training (organized with SkillsMatter), tutorials or some community events.Tomas Petricek<img src="" class="rdecor" title="Tomas speaking at the Functional Programming eXchange 2011" style="margin-bottom:15px" /> <p>The end of the summer holiday season is getting closer. Luckily, I was in Prague last week so I actually noticed there was summer this year!</p> <p>After a few quiet months, the autumn is going to be quite busy. Microsoft's <a href="">//build/</a> conference will reveal the future of software development for Windows, but great things are going on in the F# world too. Don Syme is going to talk about <a href="">F# Information Rich Programming</a> at Progressive F# Tutorials in November, which should reveal more about F# 3.0 and type providers!</p> <p>I have quite a few speaking engagements planned already, so if you want to learn about functional programming in .NET (and become a better C# programmer) or about F# and asynchronous programming, here are a few events that you may be interested in...</p> Programming with F# asynchronous sequences, 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="" 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> Real-World F# Articles on MSDN, 10 Aug 2011 04:38:33 GMTMore than a year ago, I started working on a writing project done with Manning and MSDN team. The idea was to adapt parts of my Real-World Functional Programming book, add some new practical topics and publish the articles on MSDN under the official F# documentation. I'm happy to announce that the articles, covering ASP.NET, F# asynchronous programming and agents, charting and more are now available on MSDN!Tomas Petricek<img src="" style="float:right;margin:0px 15px 15px 15px;" /> <p>More than a year ago, Mike Stephens from <a href="">Manning</a> (who was also behind my <a href="">Real-World Functional Programming</a> book) asked me if I'd be interested in collaborating on a project for MSDN. The idea was to collaborate with Microsoft on creating some additional content for the official <a href="">F# Documentation</a>.</p> <p>A few days ago, the new content appeared on MSDN, so I finally have an excuse for the recent lack of blogging! Although the content contains a large number of new articles that are not based on my book, you can find it in the MSDN section named after my book, right under <em>Visual F#</em>. If you can't wait to check it out, here are all the links:</p> <ul> <li>The <a href="">Real-World Functional Programming</a> section on MSDN.</li> <li>The <a href=";f%5B0%5D.Value=tomas%20petricek&amp;f%5B0%5D.Type=SearchText&amp;ac=8">source code for individual chapters</a> is available on MSDN Code Gallery.</li> <li>I also published <a href="">annotated TOC with source code links</a> on my functional programming web site.</li> </ul> <p>While working on the articles, I also wrote about a few topics that we didn't use in the final version. You'll see them on my blog in the next few days, as soon as I edit them into a blog post form. <a href="">Continue reading</a> for more information about individual chapters.</p>Extending Monads with Pattern Matching (Haskell 2011), 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="">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="">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="">available below</a>.</p>Fun with parallel monad comprehensions (The Monad.Reader), 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="">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="">Issue 18</a> (together with two other interesting articles). The samples from the article can be found <a href="">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="">Continue reading on the web...</a></li> <li><a href="">Get The Monad.Reader Issue 18</a> (PDF)</li> </ul>Safer asynchronous workflows for GUI programming, 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="" style="float:right; margin:0px 0px 0px 15px;" /> <p>In the <a href="">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#, 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="" 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="">Chapter 16 of my book</a> (there is a <a href="">free excerpt</a>) and I <a href="">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> Accessing loosely structured data from F# and C# (GOTO 2011), 26 May 2011 22:51:48 GMTThis article is a summary of a talk about accessing loosely structured data from F# and C# that I gave at GOTO Copenhagen 2011. The article contains examples how to bridge the gap between external data sources and programming language at various scales.Tomas Petricek<img src="" style="float:right;margin:0px 0px 15px 15px;" /> <p>About two weeks ago, I gave a talk at <a href="">GOTO Conference</a> in Copenhagen at a very interesting .NET session organized by <a href=" /">Mark Seemann</a>. In my talk, I focused on the impedance mismatch between the data structures that are used in programming languages (such as classes in C# or records and discriminated unions in F#) and the data structures that we need to access (such as database, XML files and REST services). </p> <p>Clearly, both of the sides have <em>some structure</em> (otherwise, it wouldn't be possible to write any code against them!). Even an XML file that is returned by a REST service has some structure - although the only way to find out about the structure may be to call the service and then look at the result. In this article, I'll briefly summarize the ideas that I presented in the talk. Here are links to the slides as well as the source code from the talk: </p> <ul> <li>You can browse the slides <a href="">at SlideShare</a> or you can download them from GitHub in the <a href="">PPT format</a>.</li> <li>The source code is in my <a href="">GitHub repository</a> and can be downloaded as a single <a href="">ZIP file</a>. </li> </ul> Explicit speculative parallelism for Haskell's Par monad, 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="">A monad for deterministic parallelism</a> and it is also available on <a href="" 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="">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!, 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="">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="">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="">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="">blogged</a> <a href="">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="">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 LINQ, 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="" 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="">GOTO 2011</a>). There are also many blog posts on this topic and I explained it in details in Chapter 12 of <a href="">my book</a>, which is available as a <a href="">free sample chapter</a> (PDF).</p> <p>However, you can also use LINQ syntax for writing different types of computations. In a <a href="">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="">Links project</a> and they are now used in commercial products like <a href="">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="">F# formlets by Mauricio Scheffer</a>.</p> Beyond the Monad fashion (I.): Writing idioms in LINQ, 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> MonoDevelop &amp; Teaching F# &amp; QCon tutorial, 09 Mar 2011 16:01:39 GMTIt appears that I have been doing a lot more talking than writing in the last two months. This blog post provides links to materials from my recent F# talks, including MonoDevelop presentation, talk about Teaching F# and recent QCon tutorial with Phil Trelford.Tomas Petricek<div style="float:right;text-align:center;font-size:small;margin:10px;"> <img src="" style="margin-bottom:5px" /><br /> Point of sale application from QCon tutorial </div> <p>It appears that I have been doing a lot more talking than writing in the last two months. I'm hoping to change this direction and I have two articles almost ready, so stay tuned! I was also posting all my interesting F# snippets to <a href=""></a>, which has grown quite a bit since I announced it in the last blog post. Thanks to everybody who submitted their snippets already and I'm looking forward to more! By the way, you can now run snippets using <a href=""></a> by clicking at "Load in TryF#" button.</p> <p>In the meantime, the queue with talk materials that I wanted to post on my blog has grown to 3. I talked about F# in MonoDevelop in the <a href="">Mono room at FOSDEM</a> in February, then I did an online talk for the <a href="">Community for F# </a>. Finally, this week, I did a tutorial on F# with <a href="">Phil Trelford</a> at QCon in London (to fill in for Michael Stal due to unexpected health reasons).</p> <p>Before I move on to writing about my recent experiments with LINQ, you can find materials from all of the recent talks below... </p>Announcing F# snippets web site, 12 Dec 2010 02:19:34 GMTWhen writing F# code, I often write some nice code snippet or helper function that I'd like to share with the F# community. Unfortunately, there was no good website for easy sharing of F# snippets - until today.Tomas Petricek<a href=""> <img src="" class="rdecor" style="border:0px" /> </a> <p>When writing F# programs, I often write some nice code snippet or some useful helper function that I'd like to share with the F# community. Unfortunately, my blog posts are usually longer and more elaborate, so I never get to blogging about it. Now that I have a twitter (<a href="">follow me if you don't already</a>) I thought I could just post the snippet somewhere, but there was no good web site for posting F# snippets - until now! </p> <ul> <li>If you can't wait any further, then go directly to the new F# snippets web site at <a href=""></a>. </li> </ul> <p>The web site uses my earlier project <a href="">F# Web Snippets</a> to format F# source code. It highlights colors and adds JavaScript tooltips using services provided by the F# compiler, which means that you'll get almost the same experience as when reading code in Visual Studio. I also wanted to make the page a repository of browsable snippets, so you can use it in two ways...</p>F# in Education &amp; Concurrency with Agents, 30 Nov 2010 19:18:13 GMTThis article contains materials for two talks that I had in November. First, I presented the F# plugin for MonoDevelop at the F# in Education workshop in Boston (using 3D functional library) and then I talked about agent-based concurrency (with Twitter and image processing examples) in London.Tomas Petricek<img src="" class="rdecor" /> <p>November was quite a busy month for me. First, I traveled to Cambridge (the "new one" in Massachusetts :-)) to present my work on the F# plugin for MonoDevelop at the F# in Education workshop. Shortly after getting back to London, I started working on a presentation about Concurrent Programming with Agents at the F#unctional Londoners meeting. </p> <p>Now that both of the events are over, I'd like to write a short summary and also finally publish my slides and demos. In addition, both of the events were recorded (thanks to External Research group at MSR and SkillsMatter), so if you missed them, you can watch the recording...</p> <p>Both of the events were really great and I had a chance to meet quite a few interesting people. One of the things that make F# great is the community around it. I think that one unique aspect of the F# community is its diversity. The same language is appealing to high school teachers, academics and researchers as well as software developers and technical directors from the industry. This combination is really valuable for both sides. It helps to transfer ideas from research to practice it gives researchers clear picture of problems in the industry that deserve their attention.</p> Concurrent programming with F# agents in London, 23 Nov 2010 04:40:01 GMTJust a quick reminder for everybody living near London interested in F# - I'll be giving a talk about concurrent programming using F# agents on Wednesday. We'll look at the <code>MailboxProcessor</code> type and at some common patterns for working with it.Tomas Petricek<p>If you live anywhere near London and are interested in F#, then you probably already follow the <a href="" type="external">F#unctional Londoners</a> group started by Carolyn Miller and <a href="" type="external">Phil Trelford</a>. I gave a talk at the user group in June about <a href="">Reactive programming in F#</a> (if you missed that, you can view <a href="">the recording</a>). I really enjoyed talking to an audience where most of the people already played with F#, so when I met with Phil recently, I couldn't resist offering another presentation.</p> <p>My next talk will be about <strong>Concurrent programming with Agents</strong> using the <code>MailboxProcessor</code> type. A part of the talk will be inspired by my recent blog series <a href="">about parallel programming</a>, but I just finished another pretty cool example, so you should come even if you read my blog! This time, we'll have two talks, so you can also look forward to Phil Trelford's <strong>Behaviour Driven Development with TickSpec</strong> (you just cannot miss his debugging demo!).</p> <img src="" style="float:right; margin:10px" /> <h2>When, what &amp; where?</h2> <ul> <li><strong>See also: <a href="" type="external">Concurrency with Agents and BDD with TickSpec</a></strong> at F#unctional Londoners</li> <li><strong>Date &amp; time:</strong> 24 November (Wednesday), 7:00 PM</li> <li><strong>Location:</strong> The Skills Matter eXchange, 116-120 Goswell Road, London</li> </ul> <p>Last time, I brought a copy of my <a href="" type="external">Real-World Functional Programming</a> as a giveaway and I think I still have a few copies lying around...</p> <h2>Talk teaser: F# agents</h2> <p>F# agents (the <code>MailboxProcessor</code> type) are an implementation of message passing concurrency. This is a very attractive alternative to shared memory or even standard task-based or data-parallel concurrency models. It makes it easy to write reactive applications that receive inputs from various sources in parallel (e.g. user interface, network, background tasks etc.) Agents communicate by sending (immutable) messages to each other, which makes the application easy to understand. If you design the application correctly (and structure it using enough agents) it can be also very scalable. Among other things, I'll show the following examples:</p> <ul> <li><strong>Agent-based chat</strong> - A simple example to introduce agents will be a chat room that uses agent to store the state of a chat. You'll see that an asynchronous and concurrent application can be written quite easily with F#. You'll also see how to expose this service using a few lines of beautiful F# code inspired by <code>Node.js</code>.</li> <li><strong>Reusable agents, buffering and blocking</strong> - We'll also look at a few agents that are not directly bound to any application and you can use them to implement common communication patterns. If you have a few agents like this, you can easily put together a sophisticated application just by composing existing agents.</li> </ul> Asynchronous C# and F# (III.): How does it work?, 21 Nov 2010 03:15:38 GMTIn this article, we look at the internals of asynchronous programming models in F# and a future version of C#. We compare the compilation in C# (based on state machines) and the compilation in F# (based on combinators) and we look at advantages and disadvantages of both of the approaches.Tomas Petricek<p>Some time ago, I started writing a series about the differences between the asynchronous model in F# (in Visual Studio 2010) and the asynchronous language extensions for C# proposed at PDC 2010. In the <a href="">first article</a>, I showed how both of the language features look and I highlighted a couple of differences. In the <a href="">second article</a>, I discussed the support for cancellation (available only in F#) and how the two models differ <em>semantically</em> (i.e. what are differences in the behaviour). However, I didn't talk about more techincal differences and, in particular, how is the asynchronous code compiled. We'll look at this topic today...</p> <p>Although the C# asynchronous programming model is very similar to F# asynchronous workflows, the compilation looks quite different. The C# compiler uses a similar technique as when compiling iterators and creates a state machine, while the F# compiler uses an approach based on higher order functions (combinators) that's shared with (most) other computation expressions.</p> <p>I won't discuss the syntax of F# asynchronous workflows or the C# asynchronous extensions in this article, so if you're new to one of these, here are links to other articles in this series: </p> <ul> <li><a href="">Asynchronous C# and F# (I.): Simultaneous introduction</a></li> <li><a href="">Asynchronous C# and F# (II.): How do they differ?</a></li> <li><strong>Asynchronous C# and F# (III.): How does it work?</strong></li> <li>Asynchronous C# and F# (IV.): Calling F# libraries from C# <em>(not yet available)</em></li> </ul> <p>Let's start by looking at the mechanism used in the C# compiler. If you already know how iterators work in C# 2.0, then you'll find it quite easy to understand. If you're not familiar with iterators, then don't worry - I'll make the explanation self-contained.</p> F# community on GitHub &amp; MonoDevelop update, 19 Nov 2010 14:01:37 GMTIf you're interested in the open-source release of F# or the F# plugin for MonoDevelop, you can now find them on GitHub. I started F# community organization that will manage the two projects. You can also join our mailing-list to receive all updates related to open-source community.Tomas Petricek<img src="" class="rdecor" /> <p>When I talked with Miguel de Icaza and Michael Hutchinson at the <a href="">F# in Education workshop</a> some time ago, someone mentioned that it would be nice to have a clone of the official F# code drop that could accept patches from the community. I also talked with Michael about <a href="">GitHub</a> and I think I finally understood why everybody uses it today. I said to myself that I'll need to take a look at it when I'll have a bit of time... After coming back from the workshop, I was quite busy getting the F# plugin for MonoDevelop out, but after I wrote about it, I finally found some time to look at <a href="">GitHub</a>.</p> <p>I really like the way Mono team uses GitHub. They have a single "mono" organization that is owned by several people from the Mono community and all important projects that are parts of Mono have their repository as part of the "mono" organization. Thanks to GitHub, everyone can easily clone the repository, do some changes and submit a "pull request" to the main repository.</p> <p>I thought that the F# community could follow the same model, so I started the <a href="">F# community organization</a> on GitHub...</p> F# in MonoDevelop and cross-platform web sites &amp; screencasts, 16 Nov 2010 02:35:20 GMTThe first version of the F# language binding for MonoDevelop is now available. Using the F# compiler service, it provides autocompletion, information tool tips and background type-checking. For more information and installation instructions, watch two screencasts showing F# on LinuxTomas Petricek<p>About a week ago, I attended the F# in Education workshop in Boston. It was a great event with many interesting people around. I believe that the workshop was very exciting for everyone who is interested in F#, but uses Mac or Linux. The F# team recently made some effort to improve the F# support on Mono (meaning mainly Mac and Linux). The recent <a href="" type="external">November 2010 CTP update</a> contains several bugfixes that make it possible to use F# on Mono 2.8. Another great thing that happened at the workshop is the <a href="" type="external">open source release of F#</a> (see also <a href="" type="external">blog post</a> by Miguel with a post-check-in photo). At the workshop, I also announced my contribution to the cross-platform F# story, a project that I've been working on recently - <strong>the F# language binding for MonoDevelop.</strong> </p> <div class="rdecor" style="text-align:center;"> <a target="_blank" href=""><img src="" style="border:0px;margin-bottom:5px" /></a><br /> <a target="_blank" href=""><small>Click here for a larger screenshot</small></a> </div> <p>I promised to make it available as soon as possible after the workshop. As usually, things take longer, than one would like, but I'm finally ready to announce the initial (beta) version of the plugin. The screenshot on the right shows some of the features of the F# language binding. As you can see, there is an F# Interactive tool window, syntax highlighting as well as IntelliSense auto-completion.</p> <p>If you're interested in trying it out, here are links to the repository (you can use it to install the language binding from the MonoDevelop Add-ins manager) and source code. The F# plugin needs to be able to locate F# installation and it also requires more F# assemblies to be installed in the GAC, so you may as well want to read the instructions before trying it :-).</p> <ul class="spaces"> <li><a href="" type="external">Project homepage</a> at the Functional Variations web site has more information about the project as well as detailed installation instructions.</li> <li>I also created a web page that contains information about <a href="" type="external">installing F# on Mac and Linux</a> which explains how to install F#, such that the MonoDevelop plugin can find it.</li> <li>The source code is available in the <a href="" type="external">F# cross-platform packages and samples</a> project at CodePlex (under the Apache 2.0 license). You can find it in the <code>monodevelop</code> subdirectory.</li> <li>Online repositiory with a MonoDevelop package is available at: <a href=""></a>.<br /> <em>(If you're a hacker, the easiest way to get it working is to add <code>FSharp.Compiler*</code> to GAC and set <code>FSHARP_COMPILER_BIN</code> environment variable to F# installation location)</em></li> </ul> <p>If you want to see some interesting uses of the F# MonoDevelop plugin, you can also watch <a href="" type="external">my talk at the F# in Education event</a>. In one demo, I used F# on Mac to play with a simple, composable functional 3D library. In another example I demonstrated how to asynchronously process stock prices on Linux. The last demo, showing my <code>match!</code> extension didn't work all that well, because I had too many virtual machines running, but I'll blog about <code>match!</code> again sooner or later!</p> <p>In addition to the F# plugin for MonoDevelop itself, I'd also like to mention two web sites that I've been working on and some interesting cross-platform F# screencasts...</p> Asynchronous C# and F# (II.): How do they differ?, 01 Nov 2010 16:36:00 GMTThe asynchronous programming support in C# announced at PDC 2010 is largely inspired by F# asynchronous workflows. In this article we look at some of the differences between the two including cancellation support in F# and the distinction between "hot task" model of C# and "task generator" model of F#.Tomas Petricek<p>Anders Hejlsberg announced the support for asynchronous programming in the next version of C# announced at PDC 2010. The extension looks very similar to F# asynchronous workflows (which are already available in Visual Studio 2010). Despite the large similarity, there are a couple of differences between the two programming models. I already mentioned some of them briefly in <a href="">the first article of this series</a>. In this article, we'll look at some of the technical differences between the two models.</p> <p>The most notable non-technical difference is that F# asynchronous workflows are already available in a supported version of Visual Studio and can be used on a large number of .NET runtimes (including, for example, Windows Phone and Silverlight). However, there are surprisingly many technical differences as well. In this article, I'll talk about the support for cancellation, which is available in F# and is not (currently) available in the C# preview. We'll also look at the difference between model where tasks are created as running and the delayed model.</p> <p>This article is the second part of a short series about the asynchronous programming support in C# and F#. The previous article shows a simple example in both of the languages and the next articles explain how does the feature work (and how you can customize its behavior) as well as how to call F# libraries from C#:</p> <ul> <li><a href="">Asynchronous C# and F# (I.): Simultaneous introduction</a></li> <li><strong>Asynchronous C# and F# (II.): How do they differ?</strong></li> <li><a href="">Asynchronous C# and F# (III.): How does it work?</a></li> <li>Asynchronous C# and F# (IV.): Calling F# libraries from C# <em>(not yet available)</em></li> </ul> <p>Let's start by looking at, perhaps, the most important technical difference - the built-in support for cancellation available in F# asynchronous workflows.</p> Asynchronous C# and F# (I.): Simultaneous introduction, 29 Oct 2010 04:34:51 GMTOne of the exciting new technologies announced at PDC 2010 is a preview of asynchronous programming support for C#. In this article, I briefly introduce the new features and I demonstrate how they relate to F# asynchronous workflows already available in Visual Studio 2010. We'll also look at some differences between the two.Tomas Petricek<img src="" style="float:right;margin:5px;margin-left:20px;" /> <p>One of the exciting new technologies that was announced at <a href="">PDC 2010</a> is the support for <em>asynchronous programming</em> in C#. So what exactly is <em>asynchronous programming</em>? Many applications today need to connect to some service or external data source including, for example, Web Services and REST APIs. This calls may take a long time to run, but we want to run them without blocking the application.</p> <p>Currently, you can run the operation on a background thread or using a <code>Task</code>, but coordinating multiple such operations is difficult. What if you for example need to wait until any (or all) of downloads complete and run some more code then? This is not only difficult, but it also scales badly, because blocking .NET threads is a bad practice (Threads are expensive and when they're just waiting for other operation to complete, we're wasting valuable resources). This problem has been the main motivation for including <em>asynchronous workflows</em> in F# about 3 years ago. In F#, this also enabled various interesting programming styles - for example <a href="" type="external">creating GUI using asynchronous workflows</a> (also discussed in Chapter 16 of <a href="">my book</a> and in in <a href="">my recent talk</a>). The C# asynchronous programming support and the <code>await</code> keyword is largely inspired by F# <em>asynchronous workflows</em> (I was quite surprised that F# wasn't more visibly mentioned in the PDC talk). </p> <p>In this article series, I'll demonstrate both F# and C# asynchronous programming model, I'll look at features that are missing in one or the other as well as a few subtle differences (that may be unexpected) and finally, I'll write about writing (asynchronous) F# libraries that are easy to use from C#. The plan for the series is following:</p> <ul> <li><strong>Asynchronous C# and F# (I.): Simultaneous introduction</strong></li> <li><a href="">Asynchronous C# and F# (II.): How do they differ?</a></li> <li><a href="">Asynchronous C# and F# (III.): How does it work?</a></li> <li>Asynchronous C# and F# (IV.): Calling F# libraries from C# <em>(not yet available)</em></li> </ul> <p>Let's start with a brief overview of asynchronous programming features in C# and F#...</p> F# Parallel Extras (III.): Financial dashboard with cancellation, 27 Oct 2010 11:13:08 GMTIn this article, we revisit an F# implementation of a financial dashboard example from Parallel Programming with .NET. The article explains and demonstrates how to use the built-in support for cancellation in F# asynchronous workflows.Tomas Petricek<p>In this article we'll look at several improvements that can be done to the Financial dashboard example (originally from the <a href="" type="external">Parallel Programming with Microsoft .NET</a> book). When I was translating samples in the book from C# to F#, the sample struck me, because it looks like a perfect fit for F# asynchronous workflows (instead of the <code>Task&lt;T&gt;</code> type used in the C# version). I already talked about an <a href="">alternative implementation</a> based on asynchronous workflows. However that version was still following some of the programming patterns, from the original C# version, which are not idiomatic in F#. In this article, I'll talk about a few other improvements that we can make to the sample...</p> <p>In the original version of the sample (in both C# and F#), we explicitly checked whether a cancellation token has been cancelled in every single operation. This was needed in C#, because tasks do not support cancellation automatically. However, F# asynchronous workflows make cancellation easier. They automatically check if the computation should be cancelled at the beginning and the end of every asynchronous call. Our first change will be to use this feature. Also, the original version propagates a <code>null</code> value when the computation is cancelling. In F# we don't need that and we'll only change the type of the overall result to <code>option&lt;T&gt;</code>, so that we can notify the user interface (but we don't need to propagate cancellation explicitly). Finally, the original version contained sequential implementation, but didn't provide any way of actually running it, so we'll do a bit of refactoring to make that sample actually useable.</p> F# Parallel Extras (II.): Agent-based blocking queue, 27 Oct 2010 11:12:08 GMTIn this article, we'll look at type that implements an (asynchronous) blocking queue using F# agents. This can be used, for example, when implementing the pipeline pattern as demonstrated in the <a href="">previous article</a>.Tomas Petricek<p>In the <a href="">previous article</a>, we briefly introduced the <code>BlockingQueueAgent&lt;T&gt;</code> type and we used it to implement the pipeline pattern (from Chapter 7 of <a href="" type="external">Parallel Programming with Microsoft .NET</a>) using asynchronous workflows. The type was used to represent intermediate buffers with a limited size. In this article we'll take a look at the implementation of the type. The type implements a very useful pattern in agent-based parallel programming, so you can use it in your work, but it could be also interesting as a demonstration of the F# <code>Agent&lt;T&gt;</code> type (an recommended alias for the <code>MailboxProcessor&lt;T&gt;</code> type).</p> <p>The <code>BlockingQueueAgent&lt;T&gt;</code> type is similar to <code>BlockingCollection&lt;T&gt;</code> from .NET 4.0. It has methods for adding and removing elements that block when the operation cannot be done (e.g. adding when the queue is full or removing when the queue is empty). The most important difference is that it can be used <em>asynchronously</em>. This means that when we call its operations form F# asynchronous workflow (using <code>let!</code> and <code>do!</code>), the operation will block the calling workflow, but it will not block any physical thread. We start by looking at the overall structure of the agent and then look at the body of the agent which implements its behavior (using a state machine)...</p> F# Parallel Extras (I.): Image pipeline using agents, 27 Oct 2010 11:11:08 GMTIn this article, we look at an F# implementation of an image processing pipeline demo from the Parallel Programming with Microsoft .NET. We'll use message-passing and asynchronous workflows, which leads to a more elegant and similarly efficient code.Tomas Petricek<p>In a <a href="">recent blog post series</a>, I wrote about parallel programming samples that accompany the <a href="" type="external">Parallel Programming with Microsoft .NET</a> book by patterns &amp; practices group at Microsoft. The F# translation of the samples that I wrote about mostly followed the style used in the book, so it used patterns that are typical for C#. However, some of the samples can be written in F# in a more interesting way...</p> <p>In this article, we'll take a look at agent-based implementation of the Image pipeline example (from chapter 7). A <em>pipeline</em> is a useful pattern if you need to process large number of inputs in parallel and the processing consists of multiple phases or steps. In the original implementation, the pipeline was implemented using <code>BlockingCollection&lt;T&gt;</code> and <code>Task&lt;T&gt;</code> types from .NET 4.0.</p> <p>In this article, I'll show a version that uses F# agents and asynchronous workflows. We'll use a <code>BlockingQueueAgent&lt;T&gt;</code> type, which is <a href="">discussed in another article</a>. It represents a queue with limited capacity that asynchronously blocks the process that is adding values if there is no space in the buffer and blocks the process that reads values when there are no values. This type can be elegantly used to implement the pipeline pattern. In this article, we'll demonstrate it by writing a four-phase pipeline that processes images. As you'll see, the agent-based version of the code is very much easier to write and has similar performance as the original version.</p> Reactive, parallel and concurrent programming in F# (PADL 2011), 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="" 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="">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="">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=""></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> Formatting F# source code for the Web, 18 Oct 2010 01:42:38 GMTReading F# source code in Visual Studio is much easier than in plain text, because the background type checker provides useful information about types, functions and members via tool tips. This article introduces a tool that makes it possible to bring the same user experience to your F# code snippets published on the Web.Tomas Petricek<img src="" style="float:right;margin:10px 5px 10px 10px" /> <p>Languages with type-inference make it possible to write shorter code, because a smart compiler infers the types automatically. Even though we don't write the types, they are still there and are used to check whether our code doesn't contain (certain type of) bugs. However, types are not only useful for safety, but also when understanding code. When you see a function together with its type (especially higher-order functions) you can understand code much more easily than when you just see its name. When writing F# code, you can see all the types thanks to great integration for Visual Studio. However, what if you post a code sample to a web site or a blog? Many F# code snippets (including some on this blog) are just difficult to read without types. </p> <p>A few weeks ago, I was talking with James Margetson (from the F# team) about the possible uses of some functionality provided by the F# compiler and he suggested that we could use them to solve the problem I described in the introduction. Wouldn't it be nice if you could place a mouse cursor over an identifier in an F# blog post and see the same type information as the one that would appear in Visual Studio? </p> <p>Here is an example of what I'm talking about: </p> <pre class="fssnip"> <span class="l">1: </span><span class="c">///</span><span class="c"> </span><span class="c">Asynchronously</span><span class="c"> </span><span class="c">download</span><span class="c"> </span><span class="c">the</span><span class="c"> </span><span class="c">content</span><span class="c"> </span><span class="c">of</span><span class="c"> </span><span class="c">a</span><span class="c"> </span><span class="c">web</span><span class="c"> </span><span class="c">page</span> <span class="l">2: </span><span class="k">let</span> <span onmouseout="hideTip(event, 'ftp8', 43)" onmouseover="showTip(event, 'ftp8', 43)" class="i">downloadUrl</span> <span onmouseout="hideTip(event, 'ftp9', 44)" onmouseover="showTip(event, 'ftp9', 44)" class="i">url</span> <span class="o">=</span> <span onmouseout="hideTip(event, 'ftp33', 45)" onmouseover="showTip(event, 'ftp33', 45)" class="omitted">(...)</span> <span class="l">3: </span> <span class="l">4: </span><span class="c">///</span><span class="c"> </span><span class="c">Download</span><span class="c"> </span><span class="c">specified</span><span class="c"> </span><span class="c">pages</span><span class="c"> </span><span class="c">and</span><span class="c"> </span><span class="c">add</span><span class="c"> </span><span class="c">their</span><span class="c"> </span><span class="c">lengths</span> <span class="l">5: </span><span class="k">let</span> <span onmouseout="hideTip(event, 'ftp22', 46)" onmouseover="showTip(event, 'ftp22', 46)" class="i">getTotalLength</span> <span onmouseout="hideTip(event, 'ftp23', 47)" onmouseover="showTip(event, 'ftp23', 47)" class="i">urls</span> <span class="o">=</span> <span onmouseout="hideTip(event, 'ftp10', 48)" onmouseover="showTip(event, 'ftp10', 48)" class="i">async</span> { <span class="l">6: </span> <span class="k">let!</span> <span onmouseout="hideTip(event, 'ftp24', 49)" onmouseover="showTip(event, 'ftp24', 49)" class="i">texts</span> <span class="o">=</span> <span class="l">7: </span> <span onmouseout="hideTip(event, 'ftp23', 50)" onmouseover="showTip(event, 'ftp23', 50)" class="i">urls</span> <span class="o">|&gt;</span> <span onmouseout="hideTip(event, 'ftp25', 51)" onmouseover="showTip(event, 'ftp25', 51)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'ftp26', 52)" onmouseover="showTip(event, 'ftp26', 52)" class="i">map</span> <span onmouseout="hideTip(event, 'ftp8', 53)" onmouseover="showTip(event, 'ftp8', 53)" class="i">downloadUrl</span> <span class="l">8: </span> <span class="o">|&gt;</span> <span onmouseout="hideTip(event, 'ftp27', 54)" onmouseover="showTip(event, 'ftp27', 54)" class="i">Async</span><span class="o">.</span><span onmouseout="hideTip(event, 'ftp28', 55)" onmouseover="showTip(event, 'ftp28', 55)" class="i">Parallel</span> <span class="l">9: </span> <span class="k">return</span> <span onmouseout="hideTip(event, 'ftp24', 32)" onmouseover="showTip(event, 'ftp24', 32)" class="i">texts</span> <span class="o">|&gt;</span> <span onmouseout="hideTip(event, 'ftp29', 56)" onmouseover="showTip(event, 'ftp29', 56)" class="i">Seq</span><span class="o">.</span><span onmouseout="hideTip(event, 'ftp30', 57)" onmouseover="showTip(event, 'ftp30', 57)" class="i">sumBy</span> <span onmouseout="hideTip(event, 'ftp31', 58)" onmouseover="showTip(event, 'ftp31', 58)" class="i">String</span><span class="o">.</span><span onmouseout="hideTip(event, 'ftp32', 59)" onmouseover="showTip(event, 'ftp32', 59)" class="i">length</span> }<a target="_blank" class="fssniplink" href="">F# Web Snippets</a> </pre> <p>If you cannot wait and want to create F# source code snippets like this yourself, then go straight to <a href="">F# Web Snippets</a> (please use the web based version carefully - processing is pretty demanding!). If you first want to know how it works and how to use it, as well as where to get the source code, then continue reading...</p> <!-- HTML code for ToolTips --> <div class="tip" id="ftp1">namespace System<br /></div> <div class="tip" id="ftp2">namespace System.IO<br /></div> <div class="tip" id="ftp3">namespace System.Net<br /></div> <div class="tip" id="ftp4">namespace Microsoft<br /></div> <div class="tip" id="ftp5">namespace Microsoft.FSharp<br /></div> <div class="tip" id="ftp6">namespace Microsoft.FSharp.Control<br /></div> <div class="tip" id="ftp7">module WebExtensions<br /><br />from Microsoft.FSharp.Control<br /></div> <div class="tip" id="ftp8">val downloadUrl : string -&gt; Async&lt;string&gt;<br /><br />Full name: Untitled.downloadUrl <br /><br /><em>Asynchronously download the content of a web page</em><br /></div> <div class="tip" id="ftp9">val url : string<br /><br />  type: string<br />  implements: IComparable<br />  implements: ICloneable<br />  implements: IConvertible<br />  implements: IComparable&lt;string&gt;<br />  implements: seq&lt;char&gt;<br />  implements: Collections.IEnumerable<br />  implements: IEquatable&lt;string&gt;<br /></div> <div class="tip" id="ftp10">val async : AsyncBuilder<br /><br />Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.async<br /></div> <div class="tip" id="ftp11">val req : WebRequest<br /><br />  type: WebRequest<br />  implements: Runtime.Serialization.ISerializable<br />  inherits: MarshalByRefObject<br /></div> <div class="tip" id="ftp12">type HttpWebRequest =<br />  class<br />    inherit System.Net.WebRequest<br />    member Abort : unit -&gt; unit<br />    member Accept : string with get, set<br />    member AddRange : int -&gt; unit<br />    member AddRange : int * int -&gt; unit<br />    member AddRange : string * int -&gt; unit<br />    member AddRange : string * int * int -&gt; unit<br />    member Address : System.Uri<br />    member AllowAutoRedirect : bool with get, set<br />    member AllowWriteStreamBuffering : bool with get, set<br />    member AutomaticDecompression : System.Net.DecompressionMethods with get, set<br />    member BeginGetRequestStream : System.AsyncCallback * obj -&gt; System.IAsyncResult<br />    member BeginGetResponse : System.AsyncCallback * obj -&gt; System.IAsyncResult<br />    member ClientCertificates : System.Security.Cryptography.X509Certificates.X509CertificateCollection with get, set<br />    member Connection : string with get, set<br />    member ConnectionGroupName : string with get, set<br />    member ContentLength : int64 with get, set<br />    member ContentType : string with get, set<br />    member ContinueDelegate : System.Net.HttpContinueDelegate with get, set<br />    member CookieContainer : System.Net.CookieContainer with get, set<br />    member Credentials : System.Net.ICredentials with get, set<br />    member EndGetRequestStream : System.IAsyncResult -&gt; System.IO.Stream<br />    member EndGetRequestStream : System.IAsyncResult * System.Net.TransportContext -&gt; System.IO.Stream<br />    member EndGetResponse : System.IAsyncResult -&gt; System.Net.WebResponse<br />    member Expect : string with get, set<br />    member GetRequestStream : unit -&gt; System.IO.Stream<br />    member GetRequestStream : System.Net.TransportContext -&gt; System.IO.Stream<br />    member GetResponse : unit -&gt; System.Net.WebResponse<br />    member HaveResponse : bool<br />    member Headers : System.Net.WebHeaderCollection with get, set<br />    member IfModifiedSince : System.DateTime with get, set<br />    member KeepAlive : bool with get, set<br />    member MaximumAutomaticRedirections : int with get, set<br />    member MaximumResponseHeadersLength : int with get, set<br />    member MediaType : string with get, set<br />    member Method : string with get, set<br />    member Pipelined : bool with get, set<br />    member PreAuthenticate : bool with get, set<br />    member ProtocolVersion : System.Version with get, set<br />    member Proxy : System.Net.IWebProxy with get, set<br />    member ReadWriteTimeout : int with get, set<br />    member Referer : string with get, set<br />    member RequestUri : System.Uri<br />    member SendChunked : bool with get, set<br />    member ServicePoint : System.Net.ServicePoint<br />    member Timeout : int with get, set<br />    member TransferEncoding : string with get, set<br />    member UnsafeAuthenticatedConnectionSharing : bool with get, set<br />    member UseDefaultCredentials : bool with get, set<br />    member UserAgent : string with get, set<br />    static member DefaultCachePolicy : System.Net.Cache.RequestCachePolicy with get, set<br />    static member DefaultMaximumErrorResponseLength : int with get, set<br />    static member DefaultMaximumResponseHeadersLength : int with get, set<br />  end<br /><br />Full name: System.Net.HttpWebRequest<br /><br />  type: HttpWebRequest<br />  implements: Runtime.Serialization.ISerializable<br />  inherits: WebRequest<br />  inherits: MarshalByRefObject<br /></div> <div class="tip" id="ftp13">Multiple overloads <br />WebRequest.Create(requestUri: Uri) : WebRequest <br />WebRequest.Create(requestUriString: string) : WebRequest<br /></div> <div class="tip" id="ftp14">type Uri =<br />  class<br />    new : string -&gt; System.Uri<br />    new : string * bool -&gt; System.Uri<br />    new : string * System.UriKind -&gt; System.Uri<br />    new : System.Uri * string -&gt; System.Uri<br />    new : System.Uri * string * bool -&gt; System.Uri<br />    new : System.Uri * System.Uri -&gt; System.Uri<br />    member AbsolutePath : string<br />    member AbsoluteUri : string<br />    member Authority : string<br />    member DnsSafeHost : string<br />    member Equals : obj -&gt; bool<br />    member Fragment : string<br />    member GetComponents : System.UriComponents * System.UriFormat -&gt; string<br />    member GetHashCode : unit -&gt; int<br />    member GetLeftPart : System.UriPartial -&gt; string<br />    member Host : string<br />    member HostNameType : System.UriHostNameType<br />    member IsAbsoluteUri : bool<br />    member IsBaseOf : System.Uri -&gt; bool<br />    member IsDefaultPort : bool<br />    member IsFile : bool<br />    member IsLoopback : bool<br />    member IsUnc : bool<br />    member IsWellFormedOriginalString : unit -&gt; bool<br />    member LocalPath : string<br />    member MakeRelative : System.Uri -&gt; string<br />    member MakeRelativeUri : System.Uri -&gt; System.Uri<br />    member OriginalString : string<br />    member PathAndQuery : string<br />    member Port : int<br />    member Query : string<br />    member Scheme : string<br />    member Segments : string []<br />    member ToString : unit -&gt; string<br />    member UserEscaped : bool<br />    member UserInfo : string<br />    static val UriSchemeFile : string<br />    static val UriSchemeFtp : string<br />    static val UriSchemeGopher : string<br />    static val UriSchemeHttp : string<br />    static val UriSchemeHttps : string<br />    static val UriSchemeMailto : string<br />    static val UriSchemeNews : string<br />    static val UriSchemeNntp : string<br />    static val UriSchemeNetTcp : string<br />    static val UriSchemeNetPipe : string<br />    static val SchemeDelimiter : string<br />    static member CheckHostName : string -&gt; System.UriHostNameType<br />    static member CheckSchemeName : string -&gt; bool<br />    static member Compare : System.Uri * System.Uri * System.UriComponents * System.UriFormat * System.StringComparison -&gt; int<br />    static member EscapeDataString : string -&gt; string<br />    static member EscapeUriString : string -&gt; string<br />    static member FromHex : char -&gt; int<br />    static member HexEscape : char -&gt; string<br />    static member HexUnescape : string * int -&gt; char<br />    static member IsHexDigit : char -&gt; bool<br />    static member IsHexEncoding : string * int -&gt; bool<br />    static member IsWellFormedUriString : string * System.UriKind -&gt; bool<br />    static member TryCreate : string * System.UriKind * System.Uri -&gt; bool<br />    static member TryCreate : System.Uri * string * System.Uri -&gt; bool<br />    static member TryCreate : System.Uri * System.Uri * System.Uri -&gt; bool<br />    static member UnescapeDataString : string -&gt; string<br />  end<br /><br />Full name: System.Uri<br /><br />  type: Uri<br />  implements: Runtime.Serialization.ISerializable<br /></div> <div class="tip" id="ftp15">val resp : WebResponse<br /><br />  type: WebResponse<br />  implements: Runtime.Serialization.ISerializable<br />  implements: IDisposable<br />  inherits: MarshalByRefObject<br /></div> <div class="tip" id="ftp16">member WebRequest.AsyncGetResponse : unit -&gt; Async&lt;WebResponse&gt;<br /></div> <div class="tip" id="ftp17">val stream : Stream<br /><br />  type: Stream<br />  implements: IDisposable<br />  inherits: MarshalByRefObject<br /></div> <div class="tip" id="ftp18">WebResponse.GetResponseStream() : Stream<br /></div> <div class="tip" id="ftp19">val reader : StreamReader<br /><br />  type: StreamReader<br />  implements: IDisposable<br />  inherits: TextReader<br />  inherits: MarshalByRefObject<br /></div> <div class="tip" id="ftp20">type StreamReader =<br />  class<br />    inherit System.IO.TextReader<br />    new : System.IO.Stream -&gt; System.IO.StreamReader<br />    new : System.IO.Stream * bool -&gt; System.IO.StreamReader<br />    new : System.IO.Stream * System.Text.Encoding -&gt; System.IO.StreamReader<br />    new : System.IO.Stream * System.Text.Encoding * bool -&gt; System.IO.StreamReader<br />    new : System.IO.Stream * System.Text.Encoding * bool * int -&gt; System.IO.StreamReader<br />    new : string -&gt; System.IO.StreamReader<br />    new : string * bool -&gt; System.IO.StreamReader<br />    new : string * System.Text.Encoding -&gt; System.IO.StreamReader<br />    new : string * System.Text.Encoding * bool -&gt; System.IO.StreamReader<br />    new : string * System.Text.Encoding * bool * int -&gt; System.IO.StreamReader<br />    member BaseStream : System.IO.Stream<br />    member Close : unit -&gt; unit<br />    member CurrentEncoding : System.Text.Encoding<br />    member DiscardBufferedData : unit -&gt; unit<br />    member EndOfStream : bool<br />    member Peek : unit -&gt; int<br />    member Read : unit -&gt; int<br />    member Read : char [] * int * int -&gt; int<br />    member ReadLine : unit -&gt; string<br />    member ReadToEnd : unit -&gt; string<br />    static val Null : System.IO.StreamReader<br />  end<br /><br />Full name: System.IO.StreamReader<br /><br />  type: StreamReader<br />  implements: IDisposable<br />  inherits: TextReader<br />  inherits: MarshalByRefObject<br /></div> <div class="tip" id="ftp21">member StreamReader.AsyncReadToEnd : unit -&gt; Async&lt;string&gt;<br /></div> <div class="tip" id="ftp22">val getTotalLength : string list -&gt; Async&lt;int&gt;<br /><br />Full name: Untitled.getTotalLength <br /><br /><em>Download specified pages and add their lengths</em><br /></div> <div class="tip" id="ftp23">val urls : string list<br /><br />  type: string list<br />  implements: Collections.IStructuralEquatable<br />  implements: IComparable&lt;List&lt;string&gt;&gt;<br />  implements: IComparable<br />  implements: Collections.IStructuralComparable<br />  implements: Collections.Generic.IEnumerable&lt;string&gt;<br />  implements: Collections.IEnumerable<br /></div> <div class="tip" id="ftp24">val texts : string []<br /><br />  type: string []<br />  implements: ICloneable<br />  implements: Collections.IList<br />  implements: Collections.ICollection<br />  implements: Collections.Generic.IList&lt;string&gt;<br />  implements: Collections.Generic.ICollection&lt;string&gt;<br />  implements: seq&lt;string&gt;<br />  implements: Collections.IEnumerable<br />  inherits: Array<br /></div> <div class="tip" id="ftp25">Multiple items <br />module List<br /><br />from Microsoft.FSharp.Collections <br /><br />--------------------<br /> <br />type List&lt;'T&gt; =<br />  | ( [] )<br />  | ( :: ) of 'T * 'T list<br />  with<br />    interface Collections.IEnumerable<br />    interface Collections.Generic.IEnumerable&lt;'T&gt;<br />    member Head : 'T<br />    member IsEmpty : bool<br />    member Item : index:int -&gt; 'T with get<br />    member Length : int<br />    member Tail : 'T list<br />    static member Cons : head:'T * tail:'T list -&gt; 'T list<br />    static member Empty : 'T list<br />  end<br /><br />Full name: Microsoft.FSharp.Collections.List&lt;_&gt;<br /><br />  type: List&lt;'T&gt;<br />  implements: Collections.IStructuralEquatable<br />  implements: IComparable&lt;List&lt;'T&gt;&gt;<br />  implements: IComparable<br />  implements: Collections.IStructuralComparable<br />  implements: Collections.Generic.IEnumerable&lt;'T&gt;<br />  implements: Collections.IEnumerable<br /></div> <div class="tip" id="ftp26">val map : ('T -&gt; 'U) -&gt; 'T list -&gt; 'U list<br /><br />Full name:<br /></div> <div class="tip" id="ftp27">Multiple items <br />type Async&lt;'T&gt;<br /><br />Full name: Microsoft.FSharp.Control.Async&lt;_&gt; <br /><br />--------------------<br /> <br />type Async<br />with<br />  static member AsBeginEnd : computation:('Arg -&gt; Async&lt;'T&gt;) -&gt; ('Arg * AsyncCallback * obj -&gt; IAsyncResult) * (IAsyncResult -&gt; 'T) * (IAsyncResult -&gt; unit)<br />  static member AwaitEvent : event:IEvent&lt;'Del,'T&gt; * ?cancelAction:(unit -&gt; unit) -&gt; Async&lt;'T&gt; (requires delegate and 'Del :&gt; Delegate)<br />  static member AwaitIAsyncResult : iar:IAsyncResult * ?millisecondsTimeout:int -&gt; Async&lt;bool&gt;<br />  static member AwaitWaitHandle : waitHandle:Threading.WaitHandle * ?millisecondsTimeout:int -&gt; Async&lt;bool&gt;<br />  static member CancelDefaultToken : unit -&gt; unit<br />  static member Catch : computation:Async&lt;'T&gt; -&gt; Async&lt;Choice&lt;'T,exn&gt;&gt;<br />  static member FromBeginEnd : beginAction:(AsyncCallback * obj -&gt; IAsyncResult) * endAction:(IAsyncResult -&gt; 'T) * ?cancelAction:(unit -&gt; unit) -&gt; Async&lt;'T&gt;<br />  static member FromBeginEnd : arg:'Arg1 * beginAction:('Arg1 * AsyncCallback * obj -&gt; IAsyncResult) * endAction:(IAsyncResult -&gt; 'T) * ?cancelAction:(unit -&gt; unit) -&gt; Async&lt;'T&gt;<br />  static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * beginAction:('Arg1 * 'Arg2 * AsyncCallback * obj -&gt; IAsyncResult) * endAction:(IAsyncResult -&gt; 'T) * ?cancelAction:(unit -&gt; unit) -&gt; Async&lt;'T&gt;<br />  static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * arg3:'Arg3 * beginAction:('Arg1 * 'Arg2 * 'Arg3 * AsyncCallback * obj -&gt; IAsyncResult) * endAction:(IAsyncResult -&gt; 'T) * ?cancelAction:(unit -&gt; unit) -&gt; Async&lt;'T&gt;<br />  static member FromContinuations : callback:(('T -&gt; unit) * (exn -&gt; unit) * (OperationCanceledException -&gt; unit) -&gt; unit) -&gt; Async&lt;'T&gt;<br />  static member Ignore : computation:Async&lt;'T&gt; -&gt; Async&lt;unit&gt;<br />  static member OnCancel : interruption:(unit -&gt; unit) -&gt; Async&lt;IDisposable&gt;<br />  static member Parallel : computations:seq&lt;Async&lt;'T&gt;&gt; -&gt; Async&lt;'T []&gt;<br />  static member RunSynchronously : computation:Async&lt;'T&gt; * ?timeout:int * ?cancellationToken:Threading.CancellationToken -&gt; 'T<br />  static member Sleep : millisecondsDueTime:int -&gt; Async&lt;unit&gt;<br />  static member Start : computation:Async&lt;unit&gt; * ?cancellationToken:Threading.CancellationToken -&gt; unit<br />  static member StartChild : computation:Async&lt;'T&gt; * ?millisecondsTimeout:int -&gt; Async&lt;Async&lt;'T&gt;&gt;<br />  static member StartImmediate : computation:Async&lt;unit&gt; * ?cancellationToken:Threading.CancellationToken -&gt; unit<br />  static member StartWithContinuations : computation:Async&lt;'T&gt; * continuation:('T -&gt; unit) * exceptionContinuation:(exn -&gt; unit) * cancellationContinuation:(OperationCanceledException -&gt; unit) * ?cancellationToken:Threading.CancellationToken -&gt; unit<br />  static member SwitchToContext : syncContext:Threading.SynchronizationContext -&gt; Async&lt;unit&gt;<br />  static member SwitchToNewThread : unit -&gt; Async&lt;unit&gt;<br />  static member SwitchToThreadPool : unit -&gt; Async&lt;unit&gt;<br />  static member TryCancelled : computation:Async&lt;'T&gt; * compensation:(OperationCanceledException -&gt; unit) -&gt; Async&lt;'T&gt;<br />  static member CancellationToken : Async&lt;Threading.CancellationToken&gt;<br />  static member DefaultCancellationToken : Threading.CancellationToken<br />end<br /><br />Full name: Microsoft.FSharp.Control.Async<br /></div> <div class="tip" id="ftp28">static member Async.Parallel : computations:seq&lt;Async&lt;'T&gt;&gt; -&gt; Async&lt;'T []&gt;<br /></div> <div class="tip" id="ftp29">module Seq<br /><br />from Microsoft.FSharp.Collections<br /></div> <div class="tip" id="ftp30">val sumBy : ('T -&gt; 'U) -&gt; seq&lt;'T&gt; -&gt; 'U (requires member ( + ) and member get_Zero)<br /><br />Full name: Microsoft.FSharp.Collections.Seq.sumBy<br /></div> <div class="tip" id="ftp31">type String =<br />  class<br />    new : char -&gt; string<br />    new : char * int * int -&gt; string<br />    new : System.SByte -&gt; string<br />    new : System.SByte * int * int -&gt; string<br />    new : System.SByte * int * int * System.Text.Encoding -&gt; string<br />    new : char [] * int * int -&gt; string<br />    new : char [] -&gt; string<br />    new : char * int -&gt; string<br />    member Chars : int -&gt; char<br />    member Clone : unit -&gt; obj<br />    member CompareTo : obj -&gt; int<br />    member CompareTo : string -&gt; int<br />    member Contains : string -&gt; bool<br />    member CopyTo : int * char [] * int * int -&gt; unit<br />    member EndsWith : string -&gt; bool<br />    member EndsWith : string * System.StringComparison -&gt; bool<br />    member EndsWith : string * bool * System.Globalization.CultureInfo -&gt; bool<br />    member Equals : obj -&gt; bool<br />    member Equals : string -&gt; bool<br />    member Equals : string * System.StringComparison -&gt; bool<br />    member GetEnumerator : unit -&gt; System.CharEnumerator<br />    member GetHashCode : unit -&gt; int<br />    member GetTypeCode : unit -&gt; System.TypeCode<br />    member IndexOf : char -&gt; int<br />    member IndexOf : string -&gt; int<br />    member IndexOf : char * int -&gt; int<br />    member IndexOf : string * int -&gt; int<br />    member IndexOf : string * System.StringComparison -&gt; int<br />    member IndexOf : char * int * int -&gt; int<br />    member IndexOf : string * int * int -&gt; int<br />    member IndexOf : string * int * System.StringComparison -&gt; int<br />    member IndexOf : string * int * int * System.StringComparison -&gt; int<br />    member IndexOfAny : char [] -&gt; int<br />    member IndexOfAny : char [] * int -&gt; int<br />    member IndexOfAny : char [] * int * int -&gt; int<br />    member Insert : int * string -&gt; string<br />    member IsNormalized : unit -&gt; bool<br />    member IsNormalized : System.Text.NormalizationForm -&gt; bool<br />    member LastIndexOf : char -&gt; int<br />    member LastIndexOf : string -&gt; int<br />    member LastIndexOf : char * int -&gt; int<br />    member LastIndexOf : string * int -&gt; int<br />    member LastIndexOf : string * System.StringComparison -&gt; int<br />    member LastIndexOf : char * int * int -&gt; int<br />    member LastIndexOf : string * int * int -&gt; int<br />    member LastIndexOf : string * int * System.StringComparison -&gt; int<br />    member LastIndexOf : string * int * int * System.StringComparison -&gt; int<br />    member LastIndexOfAny : char [] -&gt; int<br />    member LastIndexOfAny : char [] * int -&gt; int<br />    member LastIndexOfAny : char [] * int * int -&gt; int<br />    member Length : int<br />    member Normalize : unit -&gt; string<br />    member Normalize : System.Text.NormalizationForm -&gt; string<br />    member PadLeft : int -&gt; string<br />    member PadLeft : int * char -&gt; string<br />    member PadRight : int -&gt; string<br />    member PadRight : int * char -&gt; string<br />    member Remove : int -&gt; string<br />    member Remove : int * int -&gt; string<br />    member Replace : char * char -&gt; string<br />    member Replace : string * string -&gt; string<br />    member Split : char [] -&gt; string []<br />    member Split : char [] * int -&gt; string []<br />    member Split : char [] * System.StringSplitOptions -&gt; string []<br />    member Split : string [] * System.StringSplitOptions -&gt; string []<br />    member Split : char [] * int * System.StringSplitOptions -&gt; string []<br />    member Split : string [] * int * System.StringSplitOptions -&gt; string []<br />    member StartsWith : string -&gt; bool<br />    member StartsWith : string * System.StringComparison -&gt; bool<br />    member StartsWith : string * bool * System.Globalization.CultureInfo -&gt; bool<br />    member Substring : int -&gt; string<br />    member Substring : int * int -&gt; string<br />    member ToCharArray : unit -&gt; char []<br />    member ToCharArray : int * int -&gt; char []<br />    member ToLower : unit -&gt; string<br />    member ToLower : System.Globalization.CultureInfo -&gt; string<br />    member ToLowerInvariant : unit -&gt; string<br />    member ToString : unit -&gt; string<br />    member ToString : System.IFormatProvider -&gt; string<br />    member ToUpper : unit -&gt; string<br />    member ToUpper : System.Globalization.CultureInfo -&gt; string<br />    member ToUpperInvariant : unit -&gt; string<br />    member Trim : unit -&gt; string<br />    member Trim : char [] -&gt; string<br />    member TrimEnd : char [] -&gt; string<br />    member TrimStart : char [] -&gt; string<br />    static val Empty : string<br />    static member Compare : string * string -&gt; int<br />    static member Compare : string * string * bool -&gt; int<br />    static member Compare : string * string * System.StringComparison -&gt; int<br />    static member Compare : string * string * System.Globalization.CultureInfo * System.Globalization.CompareOptions -&gt; int<br />    static member Compare : string * string * bool * System.Globalization.CultureInfo -&gt; int<br />    static member Compare : string * int * string * int * int -&gt; int<br />    static member Compare : string * int * string * int * int * bool -&gt; int<br />    static member Compare : string * int * string * int * int * System.StringComparison -&gt; int<br />    static member Compare : string * int * string * int * int * System.Globalization.CultureInfo * System.Globalization.CompareOptions -&gt; int<br />    static member Compare : string * int * string * int * int * bool * System.Globalization.CultureInfo -&gt; int<br />    static member CompareOrdinal : string * string -&gt; int<br />    static member CompareOrdinal : string * int * string * int * int -&gt; int<br />    static member Concat : obj -&gt; string<br />    static member Concat : obj [] -&gt; string<br />    static member Concat : string [] -&gt; string<br />    static member Concat : obj * obj -&gt; string<br />    static member Concat : string * string -&gt; string<br />    static member Concat : obj * obj * obj -&gt; string<br />    static member Concat : string * string * string -&gt; string<br />    static member Concat : obj * obj * obj * obj -&gt; string<br />    static member Concat : string * string * string * string -&gt; string<br />    static member Copy : string -&gt; string<br />    static member Equals : string * string -&gt; bool<br />    static member Equals : string * string * System.StringComparison -&gt; bool<br />    static member Format : string * obj -&gt; string<br />    static member Format : string * obj [] -&gt; string<br />    static member Format : string * obj * obj -&gt; string<br />    static member Format : System.IFormatProvider * string * obj [] -&gt; string<br />    static member Format : string * obj * obj * obj -&gt; string<br />    static member Intern : string -&gt; string<br />    static member IsInterned : string -&gt; string<br />    static member IsNullOrEmpty : string -&gt; bool<br />    static member Join : string * string [] -&gt; string<br />    static member Join : string * string [] * int * int -&gt; string<br />  end<br /><br />Full name: System.String<br /><br />  type: String<br />  implements: IComparable<br />  implements: ICloneable<br />  implements: IConvertible<br />  implements: IComparable&lt;string&gt;<br />  implements: seq&lt;char&gt;<br />  implements: Collections.IEnumerable<br />  implements: IEquatable&lt;string&gt;<br /></div> <div class="tip" id="ftp32">val length : string -&gt; int<br /><br />Full name: Microsoft.FSharp.Core.String.length<br /></div> <div class="tip" id="ftp33">async { <br />  let req = HttpWebRequest.Create(Uri(url)) <br />  let! resp = req.AsyncGetResponse()<br />  let stream = resp.GetResponseStream()<br />  let reader = new StreamReader(stream)<br />  return! reader.AsyncReadToEnd() }<br /></div> Parallel Programming in F# (IV.): Financial dashboard example, 06 Sep 2010 10:30:00 GMTIn this article, we'll take a look at the Adatum Financial Dashboard sample from Parallel Programming with Microsoft .NET and we'll compare implementations using tasks and asynchronous workflows.Tomas Petricek<p>In the fourth part of the Parallel Programming in F# series, we'll take a look at the Adatum Financial Dashboard sample. The sample is a part of <a href="" type="external">Parallel Programming with Microsoft .NET</a>, which is a guide that introduces common parallel programming patterns on .NET 4.0. The C# version of the sample is in details discussed in the guide, but the F# translation contains several additional interesting aspects that I'll introduce in this article.</p> <p>The sample simulates a financial modelling application that performs processing of market data in several steps that can be partly executed in parallel. In this article we'll compare two implementations. The first one (similar to the C# version) uses the <code>Task&lt;'T&gt;</code> type from .NET 4.0 and chains steps using the <code>ContinueWith</code> method. The second version is F# specific and it implements step as a sequential computation wrapped in asynchronous workflows. Partial results are reported to the user interface using events.</p> Parallel Programming in F# (III.): Aggregating data, 06 Sep 2010 10:20:00 GMTIn this article, we'll take a look at F# samples from Chapter 4 of Parallel Programming with Microsoft .NET. We'll discuss several options for implementing the Map/Reduce pattern.Tomas Petricek<p>In this part of the Parallel Programming in F# series, we'll explore examples of parallel aggregation from Chapter 4 of <a href="" type="external">Parallel Programming with Microsoft .NET</a>, which is a guide that introduces common parallel programming patterns on .NET 4.0. The C# version of the sample is in details discussed in the guide. In this article, we'll look at the F# translation and in particular at several functions from the <code>PSeq</code> module. Some of the functionality is currently available only in the "PSeq.fs" distributed with the samples, but will eventually appear in F# PowerPack as well. </p> <p>Aggregation of data in parallel is an interesting problem. As we've seen in the previous article, PLINQ and tasks make it easy to parallelize independent blocks of code that don't share any state. Unfortunatelly, not all programs are like that. In particular, we often need to aggregate all elements of a sequence - when writing sequential code in F#, you would use the <code>Seq.fold</code> function. In this article, we'll look at functions that implement fold parallel.</p> Parallel Programming in F# (II.): Using PLINQ and Tasks, 06 Sep 2010 10:10:00 GMTIn this article, we'll look at several F# samples from Chapters 2 and 3 of Parallel Programming with Microsoft .NET. We'll look at using Task Parallel Library (TPL) and Parallel LINQ from F#, including the <code>PSeq</code> module from F# PowerPack.Tomas Petricek<p>In this part of the Parallel Programming in F# series, we'll look at some basic examples of parallel programming in F# that are available in <a href="" type="external">Parallel Programming with Microsoft .NET</a>. This is a guide that introduces common parallel programming patterns on .NET 4.0. The guide discusses the samples in C#, but it also contains an F# translation of the source code. Since the languages are different, the F# version deserves a brief explanation.</p> <p>In this article, we'll discuss some of the F# examples and we'll look at a couple of aspects that are specific for F#. In particular, we'll look at working with Parallel LINQ (both directly and using <code>PSeq</code> module from F# PowerPack) and working with tasks. We'll also look at an interesting example (using closures) where C# version doesn't behave as expected, but a literal translation in F# corrects the problem.</p> Parallel Programming in F# (I.): Introducing the samples, 06 Sep 2010 10:00:00 GMTIn this article series, I'll introduce the F# version of samples for the Parallel Programming with Microsoft .NET book written by the patterns &amp; practices group at Microsoft.Tomas Petricek<img src="" style="float:right;margin:20px;" /> <p><a href="" type="external">Parallel Programming with Microsoft .NET</a> is a guide written by the patterns &amp; practices group at Microsoft. It introduces .NET programmers to patterns for including parallelism in their applications (using support for parallel programming in .NET 4.0). It introduces techniques such as parallel loops, parallel tasks, data aggregation and so on. The book includes numerous samples in C# and Visual Basic that can be easily copied and adapted to match your needs.</p> <p>As part of a contracting work for the F# team, I developed an F# version of the samples, which is now available on the <a href="" type="external">book web site</a>. You can get it by downloading <a href="">F# code samples</a> (ZIP) from the 1.0 release, or you can download the <a href="" type="external">latest version of the source code</a> directly. The F# version of the code is mostly a direct translation of the C# versions, but there are a few interesting places that are worth discussing. In particular, some of the samples use the <code>PSeq</code> module from F# PowerPack and I also added a version of one example that uses F# asynchronous workflows.</p> <p>In this article series, I'll look at several interesting examples from the F# version of the source code. We'll look how to use PLINQ and Tasks (which are available in .NET 4.0) from F# (Part II.) including some advanced topics such as the Map-Reduce algorithm (Part III.). We'll also look at a larger example built using tasks and an alternative implementation using asynchronous workflows (Part IV.) Here are links to the individual articles:</p> <ul> <li><strong>Parallel Programming in F# (I.): Introducing the samples</strong></li> <li><a href="">Parallel Programming in F# (II.): Using PLINQ and Tasks</a></li> <li><a href="">Parallel Programming in F# (III.): Aggregating data</a></li> <li><a href="">Parallel Programming in F# (IV.): Financial dashboard example</a></li> </ul> The Duality of Object and Event references, 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=";&#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=";&#xA;#duallinks">4</a>] I wrote with <a href="">Don Syme</a> and that I presented at the ISMM Workshop (see also <a href="">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> Dynamic in F#: Reading data from SQL database, 09 Jul 2010 02:03:00 GMTIn this article we look at working with SQL databases in F# using ADO.NET. We'll see how to use dynamic invoke operator to make the usual ADO.NET code remarkably elegant and simple...Tomas Petricek<p>When reading data from a SQL database in F#, you have a couple of options. You can use F# implementation of LINQ, which allows you to write queries directly in the F# language or you can use standard ADO.NET classes such as <code>SqlCommand</code>. The second option is often good enough - when you just need to call a simple query, you probably don't want to setup the whole LINQ infrastructure (generate classes, reference F# PowerPack, etc.) Unfortunately, ADO.NET classes are a bit ugly to use. When calling an SQL stored procedure, you need to specify the name of the procedure as a string, you need to add parameters one-by-one by creating instances of <code>SqlParameter</code>, you need to dynamically cast results from the <code>obj</code> type and so on...</p> <p>In this article, we'll look how to use the <em>dynamic operator</em> to make the experience of using ADO.NET from F# dramatically better. Dynamic operator (there are actually two of them) are a simple way of supporting dynamic invoke in F#. We can use it to write code that looks almost like an ordinary method call or property access, but is resolved dynamically at runtime (using the name of the method or property). The following example shows what we'll be able to write at the end of this article:</p> <pre lang="fsharp"> // Call 'GetProducts' procedure with 'CategoryID' set to 1 use conn = new DynamicSqlConnection(connectionString) use cmd = conn?GetProducts cmd?CategoryID &lt;- 1 conn.Open() // Read all products and print their names use reader = cmd.ExecuteReader() while reader.Read() do printfn "Product: %s" reader?ProductName </pre> <p>If you ever tried to call a SQL stored procedure directly using the <code>SqlCommand</code>, then you can surely appreciate the elegance of this code snippet. Let's now take a look at a larger example and some of the neat tricks that make this possible...</p> PLDI 2010 Trip Report, 05 Jul 2010 23:23:02 GMTIn June, I attended PLDI 2010, which is one of the big "programming language" conferences. I presented a paper based on some work that I did during my internship at MSR at one of the workshops and I also attended many interesting talks...Tomas Petricek<p>In June, I attended my first "big" academic conference <a href="" type="external">Programming Languages Design and Implementation (PLDI 2010)</a> in Toronto. I attended the conference, because I presented a paper that I wrote with Don Syme as a result of my internship at Microsoft Research, but I'll write more about that shortly (and thanks to MSR for partly supporting my attendance at the conference!)</p> <p>As far as I understand it, the focus of the conference is more on <em>implementation</em>. Many people believe that the current programming languages are good enough and we need to make sure that they run well (e.g. compilers optimize code to run better on multi-core) and that we need better tools for working with them (e.g. automatic verification of the code we write), so these areas were the main focus of the conference. However, there were some very interesting talks on the <em>design</em> of programming languages, which is an area that I personally find more interesting... </p> Recording and samples from my Reactive F# talk, 27 Jun 2010 14:49:28 GMTAlmost a week ago, I <a href="">posted an invitation</a> to my F# talk at the F#unctional Londoners user group. The talk has been recorded, so you can view it online now and you can also get all the Silverlight demos...Tomas Petricek<p>Almost a week ago, I <a href="">posted an invitation</a> to my F# talk at the F#unctional Londoners user group. The theme of my talk was <em>reactive programming</em>, which was also a topic of my <a href="">Master's thesis</a> (defended earlier in June), so I really enjoyed talking about it. In the talk, I discussed the two approaches that you can use for developing reactive applications in F# (using examples in Silverlight): </p> <a href=""> <img src="" style="margin:10px; float:right; border-style:none;" /> </a> <ul> <li><strong>Declarative</strong> (or <em>data-flow</em> oriented) allows you to describe "what" should be done with data that your component receives from various events (such as mouse position etc.) This can be written using F# event combinators such as <code></code> and <code>Event.scan</code>.</li> <li><strong>Imperative</strong> (or <em>control-flow</em> oriented) - in this style, we describe various states of the component (e.g. semaphore with green, orange and red) and describe transitions between the states. This can be written using F# <em>asynchronous workflows</em> and the <code>AwaitObservable</code> primitive (which you can get as part of the source code).</li> </ul> <p>Thanks to the folks from <a href="">SkillsMatter</a> who provided place for the meetup and helped with the organization, the talk was also recorded and is already available online! Below, you can also get all the nice Silverlight demos that I used during the talk...</p> <p>Thanks again to Carolyn Miller and <a href="" type="external">Phil Trelford</a> for organizing the talk and also to <a href="">Don Syme</a> for taking me to the airport in the early morning (at 4 AM...) after the talk.</p> <h2>Links &amp; Resources</h2> <ul> <li><a href="" type="external">Reactive Programming in F#</a> (recording) - Skills Matter</li> <li>Slides from the talk (<a href="" type="external">PDF</a>, <a href="" type="external">PPTX</a> formats)</li> <li><a href="" type="external">Reactive F# demos in Silverlight</a> (includes <code>AwaitObservable</code> implementation)</li> </ul>Reactive Programming with F# in London, 15 Jun 2010 02:54:39 GMTI'll be visiting London on June 23 and I'll be talking at the F#unctional Londoners user group. The theme of the talk is Reactive Programming with F# and you can expect many interesting F# features including asynchronous workflows and event combinators.Tomas Petricek<p>If you’re a registered member of the <a href="" type="external">F#unctional Londoners</a> user group, then you maybe already know that I'll be visiting London on <strong>June 23</strong> and I’ll be talking about <strong>Reactive programming with F#</strong>. If you're not a registered member and occasionally visit London, then you should definitely register. The user group is organized by Carolyn Miller and <a href="" type="external">Phil Trelford</a> (whom I met some time ago at Microsoft Research in Cambridge). Among others, previous speakers include <a href="" type="external">Robert Pickering</a> (who also presented some samples based on my <a href="">F# and Accelerator</a> series). Finally, another reason for joining the group is that it has a great name (as well as a logo)!</p> <img src="" style="float:right; margin:10px" /> <h2>When, what &amp; where?</h2> <ul> <li><strong><a href="" type="external">Tomas Petricek on Reactive Programming with F#</a></strong></li> <li><strong>Date &amp; time:</strong> 23 June (Wednesday), 6:30 PM</li> <li><strong>Location:</strong> The Skills Matter eXchange, 116-120 Goswell Road, London</li> </ul> <p>By the way, I'll also have a free copy of my <a href="" type="external">Real-World Functional Programming</a> book to give away during the talk!</p> <h2>Reactive Programming with F#</h2> <p>I'm sure you're already convinced to come. Nevertheless, you may still want to know what I'm going to talk about. There are many areas where F# offers clear benefits such as parallel &amp; concurrent programming. I believe that <strong>reactive programming</strong> is another great area for F#. In reactive programming, we face quite different problems than in other programming styles. We (as the authors of the application) can no longer specify what the application should do. Instead, the application needs to be able to handle many possible combinations of events. This aspect of programming is sometimes called <em>inversion of control</em>.</p> <p>Reactive programming is important for programming user interfaces, especially today when user interfaces are becoming more interactive and more "fancy". To demonstrate this, I'm working on some nice <strong>Silverlight</strong> demos for the talk! However, it is also needed to handle other kinds of events such as completion of background task or message from other application. We'll look at the two essential techniques that F# provides for reactive programming:</p> <ul> <li><strong>Declarative event combinators</strong> - one way of writing reactive applications is to specify the whole event processing declaratively by saying "what" should be done with occurrences of events. This is particularly useful when we need to encode simpler logic with a clear <em>data-flow</em>.</li> <li><strong>Imperative using workflows</strong> - for more complicated interactions, we can use <em>asynchronous workflows</em>. This makes the code more explicit, but we get full control over the <em>control-flow</em> of the application. Even though this approach is more "imperative" it can be used for writing nicely composable functional code as well.</li> </ul> <p>I'm looking forward to seeing you at the talk next week!</p>ASP.NET and F# (I.) - Creating MVC web applications in F#, 09 May 2010 20:43:52 GMTThis article shows how to use F# for developing ASP.NET web applications using the MVC framework. It also shows how to access data using LINQ in F# and how to simplify web programming using F# meta-programming, modules and records.Tomas Petricek<p>Some time ago, I wrote a couple of examples of <a href=""> developing web applications in F# using ASP.NET</a>. Since then, the F# language and runtime has changed a little bit and there are also new technologies available in ASP.NET, so I thought I'd write a more up-to-date article on this topic. In this article, I'll present a simple "demo" F# web application that you can use as a starting point when creating your own projects (you'll also find a convenient Visual Studio 2010 template below). The article shows the following interesting things:</p> <ul> <li><strong>ASP.NET MVC</strong> - We're going to use ASP.NET MVC Framework to create the web application. As the article name suggests, most of the actual program code including models and controllers will be implemented in F#.</li> <li><strong>F# LINQ to SQL</strong> - The application uses a sample Northwind database and we'll write queries for selecting data from the database using LINQ support that's available in the <a href="" type="external">F# PowerPack</a>.</li> <li><strong>F# features</strong> - The application also uses some nice F# features that are quite useful for developing web applications. We'll use modules and records to implement the model and we'll also use advanced meta-programming features for constructing LINQ queries.</li> </ul> <p>If you want to use F# for creating an MVC application, you have a few options. It should be possible to create the web application solely as an F# project. However, we'll use a more convenient approach. We'll create a standard C# MVC project and move all the actual implementation to an F# library. We'll look at the application structure shortly. The following screenshot shows a page that lists products in the Northwind database:</p> <div style="text-align:center;"> <img src="" /> </div> Programming user interfaces using F# workflows, 18 Feb 2010 00:25:51 GMTF# asynchronous workflows can be used to solve a wide range of programming problems. In this article we'll look how to use asynchronous workflows for elegantly expressing the control flow of interaction with the user. We'll also look at clear functional way for encoding drag and drop-like algorithm.Tomas Petricek<p>Numerous Manning partners already published several exceprts from my <a href="" target="external">Real-World Functional Programming</a> book. You can find a list on the <a href="" type="external">book's web page</a>. However, the last excerpt published <a href="" type="external">at DotNetSlackers</a> is particularly interesting. It discusses how to use F# asynchronous workflows to write GUI applications. This is a very powerful programming pattern that is very difficult to do in any other .NET language. We first discussed it with Don Syme during my internship at Microsoft Research and I found it very elegant, so I made some space for it in the book. In fact, the entire Chapter 16 discusses various reactive programming techniques that can be used in F#.</p> <img src="" style="margin:15px;float:right;" /> <p style="padding-left:40px;padding-right:40px;font-style:italic;">When designing applications that don't react to external events, you have lots of control flow constructs available, such as if-then-else expressions, for loops and while loops in imperative languages, or recursion and higher-order functions in functional languages. Constructs like this make it easy to describe what the application does. The control flow is clearly visible in the source code, so drawing a flowchart to describe it is straightforward.</p> <p style="padding-left:40px;padding-right:40px;font-style:italic;">Understanding reactive applications is much more difficult. A typical C# application or GUI control that needs to react to multiple events usually involves mutable state. When an event occurs, it updates the state and may run more code in response to the event, depending on the current state. This architecture makes it quite difficult to understand the potential states of the application and the transitions between them. Using asynchronous workflows, we can write the code in a way that makes the control flow of the application visible even for reactive applications.</p> <p style="text-indent:0px">You can read the complete article here: <a href="">Programming user interfaces using F# workflows </a> [<a href="" target="_blank">^</a>]. It is also worth adding that Manning offers <strong>30% discount</strong> to DotNetSlackers readers (see the article for details!)</p>Using custom grouping operators in LINQ, 07 Feb 2010 20:13:32 GMTIn LINQ, we can group data using the "group by" clause. However, there are other potentially useful implementations of grouping. For example, we may want to group only adjacent elements or group ascending or descending parts of the data. This article shows how to use custom behavior when grouping data using "group by" in LINQ query.Tomas Petricek<p>You can use LINQ to write queries that perform grouping of data using <code>group by</code> or ordering of data using <code>orderby</code> clause. LINQ provides the default (and the most common) implementation of both of the operations, but sometimes you may need a slightly different behavior when grouping or ordering data (this article is motivated by a <a href="" type="external">question on StackOverflow</a> which needs to do exactly that for grouping).</p> <p>Let's look at a simple example, which shows when we may need a different behavior when grouping data. For example, we may have the following list of stock trades containing a name of a stock and the price of the trade (stored for example as a list of <code>TradeInfo</code> classes with properties <code>Name</code> and <code>Price</code>):</p> <pre lang="csharp"> { { Name = "MSFT", Price = 80.00 }, { Name = "MSFT", Price = 70.00 }, { Name = "GOOG", Price = 100.00 }, { Name = "GOOG", Price = 200.00 }, { Name = "GOOG", Price = 300.00 }, { Name = "MSFT", Price = 30.00 }, { Name = "MSFT", Price = 20.00 } }</pre> <p>Now, we may want to group adjacent trades into a single summary record which will contain the name of the stock (which is same for all trades in each group), the number of trades in the group and an average price in the group. The desired results are:</p> <pre lang="csharp"> { { Name = "MSFT", Count = 2, AvgPrice = 75.00 }, { Name = "GOOG", Count = 3, AvgPrice = 200.00 }, { Name = "MSFT", Count = 2, AvgPrice = 25.00 } }</pre> <p>The operation that we want to do is very similar to <code>group by</code> in LINQ, but it doesn't do quite the same thing! If we used <code>group by</code>, we would get only two groups as the result. However, as I wrote earlier, we want to group only <em>adjacent trades</em>. You could write your own extension method to do this, but then you need to leave the elegant LINQ query syntax. In this article, I'll show you how to get the desired results using a simple LINQ query with a <code>group by</code> clause...</p>Deal of the day: Real-World Functional Programming, 24 Jan 2010 17:00:41 GMTSome time ago, I received my copies of <strong>Real-World Functional Programming</strong>. I started working on it back in May 2008 and as many people who had more experience with writing books told me, it took longer than I was expecting!Tomas Petricek<p>Some time ago, I received my copies of <strong>Real-World Functional Programming</strong>. I started working on it back in May 2008 and as many people who had more experience with writing books told me, it took longer than I was expecting! Anyway, I have to say, it was worth it, holding the actual printed book with my name on the cover is just fantastic!</p> <br /> <a href=""><img src="" style="border:0px; float:right;margin:10px;" /></a> <p>The goal of the book is to present functional programming concepts and ideas in a readable form. I wanted to create a book that will teach you how to <em>think functionally</em> without using the usual <em>shock therapy</em> that people usually feel when seeing functional programming for the first time. There are already a couple of reviews that suggest I was quite successful:</p> <ul> <li><em>Functional Programming for the Real World, by Tomas Petricek and Jon Skeet, has been a very helpful book for moving to F# from C#, as the authors do a fantastic job of helping to explain the differences between OOP and FP. </em><br /> <a href="" type="external">James Black at</a> </li> <li><em>This book isn’t just a simple introduction to programming in F#; it’s an introductory text on functional programming covering the many reasons why it is time for this programming paradigm to finally be accepted by mainstream programmers. And it also contains much more... </em><br /> <a href="" type="external">CliveT, Software Engineer at Red Gate Software</a> </li> <li>... and there are many other great comments about the book at <a href="">Manning book page</a>.</li> </ul> <h2>Deal of the day (January 24)</h2> <p>Finally, here is one great news if you're interested in getting the book! <strong>Real-World Functional Programming</strong> is Manning's Deal of the Day this Sunday, January 24. On this day, the print book is available for $20 from the <a href="">Manning website</a>, with code <code>dotd0124</code>.</p> Accelerator and F# (IV.): Composing computations with quotations, 12 Jan 2010 03:20:36 GMTIn this article series we're talking about the Accelerator project, which can be used from F# to write code that runs in parallel on GPU or multi-core CPU. In this article, we'll look at building complex data-parallel programs with F# quotations, we'll implement blur filter and we'll also discuss architecture and performance.Tomas Petricek<p>In this article series, we're talking about the Accelerator project and I'm presenting an F# library that I implemented, which allows you to use Accelerator [<a href="">references</a>] in a more sophisticated way. We've seen two examples of using Accelerator directly (see also <a href="">introduction</a> and <a href="">Game of Life</a>). In the <a href="">previous article</a> I introduced my F# library for working with Accelerator. We've seen F# functions from the <code>DataParallel</code> module, we implemented an algorithm that rotates an image using these functions and finally, we've seen that we can take this ordinary F# code and run it using Accelerator. This is all possible thanks to F# quotations, which we can use to get an AST (a source code) of an F# function we wrote (if the function is marked in some special way).</p> <img src="" alt="Blurred photo of Prague" style="float:right; margin:10px" /> <p>In this part of the series, we're going to look at working with quotations explicitly. We'll use meta-programming techniques to work with Accelerator. Meta-programming means writing programs that manipulate with other programs or pieces of code. This is exactly what we're going to do in this article. We'll write an F# function (running on CPU) that builds a program, which we'll then run using Accelerator.</p> <p>This is quite interesting approach, which isn't possible when we call Accelerator methods as standard F# functions or .NET methods. The benefit is that we'll clearly see which parts of program run on CPU and what parts execute on GPU or using X64 multi-core target. We could also perform more complicated optimizations with the code (because this wouldn't affect the readability). Just for your reference, here is the list of articles in this series in case you missed some of them:</p> <ul> <li><a href="">Accelerator and F# (I.): Introduction and calculating PI</a></li> <li><a href="">Accelerator and F# (II.): The Game of Life on GPU</a></li> <li><a href="">Accelerator and F# (III.): Data-parallel programs using F# quotations</a></li> <li><strong>Accelerator and F# (IV.): Composing computations with quotations</strong></li> </ul> <p>However, enough with theory and let's take a look at some code samples! This time, we'll implement blurring of an image (also called convolution). Another example how to write this in F# using Accelerator is Satnam Singh's blog post [<a href="#accelfsh4links">4</a>]. Our example will be different, because we'll write the code as standard F# program and then have it translated to Accelerator automatically using quotations. We'll also talk about the architecture of the library that we're using and look at some performance results.</p> Accelerator and F# (III.): Data-parallel programs using F# quotations, 04 Jan 2010 12:50:13 GMTWe already discussed how to write programs that run on GPU using MSR Accelerator. In this article, we'll write an image rotation using data-parallel F# functions and then use a library that translates it to Accelerator automatically.Tomas Petricek<p>If you've been following this article series, you already know that Accelerator is a MSR library [<a href="">1</a>, <a href="#accelfsh3links">2</a>] that allows you to run code in parallel on either multi-core CPU or using shaders on GPU (see <a href="">introduction</a>). We also discussed a direct way to use Accelerator from F# (by calling Accelerator methods directly) and <a href="">implemented Conway's Game of Life</a>. In this article, we'll look at more sophisticated way of using Accelerator from F#. We'll introduce F# quotations and look at translating 'normal' F# code to use Accelerator.</p> <img src="" alt="Rotated Prague photo" style="float:right; margin:10px" /> <p>In general, F# quotations allow us to treat F# code as data structure and manipulate with it. This is very similar to C# expression trees, but the F# implementation is more powerful. We can also mark a standard method or a function with a special attribute that tells the compiler to store quotation of the body. Then we can access the quotation and traverse it or modify it. In this article we'll use a function that takes an F# quotation (containing a limited set of functions) and executes it using MSR Accelerator. Implementing this functionality is a bit complicated, so we won't discuss the implementation now. We'll leave this for some future article of this series. In future, we'll also look at other interesting possibilities that we have when writing code using quotations. Here is a list of articles in this series and of the articles that I'm planning to add:</p> <ul> <li><a href="">Accelerator and F# (I.): Introduction and calculating PI</a></li> <li><a href="">Accelerator and F# (II.): The Game of Life on GPU</a></li> <li><strong>Accelerator and F# (III.): Data-parallel programs using F# quotations</strong></li> <li><a href="">Accelerator and F# (IV.): Composing computations with quotations</a></li></ul> Accelerator and F# (II.): The Game of Life on GPU, 28 Dec 2009 21:16:03 GMTThis article shows how to use Accelerator from F#, which I <a href="accelerator-intro.aspx">already discussed</a>, to implement a massively parallel version of the famous Conway's Game of Life.Tomas Petricek<p>In the <a href="accelerator-intro.aspx">previous article</a>, I introduced the Microsoft Research Accelerator library. It allows us to write computations with arrays in C# and execute them in parallel on multi-core CPU or more interestingly, using GPU shaders. In the previous artcile, we've seen how Accelerator works and how it can be accessed from F#. In this article, we'll look at one more interesting F# demo - we'll implement the famous Conway's Game of Life [<a href="accelerator-life-game.aspx#accelfsh2links">1</a>] using Accelerator. We'll use a v2 version of Accelerator which has been announced just recently and is available from Microsoft Connect [<a href="accelerator-life-game.aspx#accelfsh2links">2</a>].</p> <div style="text-align:center;"> <object width="425" height="344"><param name="movie" value=";hl=en&amp;fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src=";hl=en&amp;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object> </div> <p>This article is the second one from a series about using Accelerator from F#. Today, we'll use Accelerator types directly from F# - this is the simplest possible approach and is very similar to the way you'd work with Accelerator in C#. However, we can use some nice F# features such as custom operators to make the code more readable. In the next article, we'll discuss a different approach - we'll look how to execute more "standard" F# code (that doesn't reference Accelerator explicitly) with Accelerator using F# quotations. The list of articles may change, but here is a list of articles that I'm currently planning to write:</p> <ul> <li><a href="">Accelerator and F# (I.): Introduction and calculating PI</a></li> <li><strong>Accelerator and F# (II.): The Game of Life on GPU</strong></li> <li><a href="">Accelerator and F# (III.): Data-parallel programs using F# quotations</a></li> <li><a href="">Accelerator and F# (IV.): Composing computations with quotations</a></li> </ul> Accelerator and F# (I.): Introduction and calculating PI, 21 Dec 2009 03:21:03 GMTThis article shows how to write F# programs that run in parallel as shader programs on GPU or on multi-core CPU using Microsoft Research Accelerator project.Tomas Petricek<img src="" alt="Calculating Pi using Monte-Carlo" style="float:left; margin:10px" /> <p>I already wrote about two projects that I worked on during an internship at MSR back in 2007 (<a href="" type="external">ASP.NET support in F#</a> and <a href="" type="external">F# WebTools</a>). Even though this was more than 2 years ago (and I did one more internship at MSR in the meantime), I still have one more project that I never published on the web. The folks from the F# team reminded me of this project recently, so I thought I could finally publish it. The project used Microsoft Research Accelerator [<a href="#accelfsh1links">1</a>, <a href="#accelfsh1links">2</a>], which is a C# library for developing array-based computations and executing them on a GPU. More recently, the Accelerator team at MSR published Accelerator v2 [<a href="#accelfsh1links">3</a>], which was a good motivation to update my original project...</p> <p>In this article, we'll look at the simplest way of using Accelerator from F#. Accelerator provides a managed interface that can be naturally used from both C# and F#. We can use a mix of method calls and overloaded operators to describe a computation. In F#, we'll also define our additional custom operators to make the code a bit nicer. After we introduce Accelerator using a simple C# demo, we'll look how to calculate an approximate value of the PI number using a Monte-Carlo method.</p> <p>This article is the first one from a series about using Accelerator from F#. The list of articles may change, but here is a list of articles that I'm currently planning to write:</p> <ul> <li><strong>Accelerator and F# (I.): Introduction and calculating PI</strong></li> <li><a href="">Accelerator and F# (II.): The Game of Life on GPU</a></li> <li><a href="">Accelerator and F# (III.): Data-parallel programs using F# quotations</a></li> <li><a href="">Accelerator and F# (IV.): Composing computations with quotations</a></li> </ul> Real-World Functional Programming: Completed and printed!, 19 Dec 2009 21:54:28 GMTIf you're following my blog, you probably noticed that I was working on a book about functional programming using F# and C#. The great news is that the book is finally completed and will be available on December 24!Tomas Petricek<p>If you're following my blog or if you're interested in F# or functional programming in .NET, you probably noticed that I was working on a book <a href="">Real-World Functional Programming</a>. At some point, we called it <em>Functional Programming for the Real-World</em>, but then we changed the title back to a better sounding version <em>Real-World Functional Programming</em> (subtitle <em>With examples in F# and C#</em>). The book is also reason for a lower number of blog posts over the last year. Over the last month or so, we were doing the final edits, reviewing the final PDF version (I fixed quite a lot minor issues, synchronized book with the Beta 2 F# release and so on). Anyway, before a few days, I received the following email (as an author, I receive the same emails as those who ordered the book through the <a href="">Manning Early Access Program</a>, so that I can see what we're sending to our dear readers):</p> <table><tr><td> <img style="margin:10px" src="/articles/book-completed/cover.png" /> </td><td> <p style="font-style:italic; margin:10px 30px 10px 10px; text-indent:0px;"> Dear Tomas Petricek, <br /> We are pleased to announce that <strong>Real-World Functional Programming</strong> is now complete! As a MEAP subscriber you can download your copy of the finished ebook right now! (...) This ebook is the final version, identical to the softbound edition, which is currently being printed and will be available on <strong>December 24</strong>. If you chose the printed book option when you originally subscribed, we'll ship it to you automatically—no action required from you. </p> </td></tr></table> <h2>Finally finished!</h2> <p>Yes, that's right. The book is finally completed and as far as I know, it has been printed last week! If you already ordered the book, you won't receive it before Christmas, but it should come shortly after. I can't wait to see the book actually <em>printed</em>. The transition from the Word drafts I initially wrote to a final PDF version was already felt fantastic and I thought <em>"It looks like a real book!"</em> Among other things, there are now graphical arrows with comments inside listings, which looks really great and makes code listings much easier to read. Now I can look forward to seeing the <em>actual book</em>. Maybe I'm too conservative, but I have to say that I'm really glad that I wrote the book before everything is going to be published just electronically!</p> <p>Here is a couple of links that you may found interesting if you want to look inside the book...</p>Functional Programming: Available Chapter Excerpts &amp; Discount, 26 Jul 2009 03:41:14 GMTThe work on my book Functional Programming for the Real World is slowly getting to the end. If you want to look inside, you can read some of the chapter excerpts that were published on the internet.Tomas Petricek<p>The work on my book <a href="" target="external">Functional Programming for the Real World</a> is slowly getting to the end. I'm currently creating index for the last couple of chapters and doing final updates based on the feedback from reviews and also from the <a href=";start=0" type="external">forum at</a> (this means that if you have some suggestions, it's the best time to post them - I haven't yet replied to all of them, but I'll certainly do that before the manuscript will go to the production).</p> F# Webcast (IV.) - Developing standard .NET libraries, 15 Jun 2009 20:09:04 GMTThis webcast demonstrates how to wrap an existing F# code into an object oriented library that can be nicely used from C# and how to use it when developing ASP.NET web application. The demo uses script for processing RSS feeds from the previous webcast.Tomas Petricek<p>In the previous parts of this webcast series we've developed an F# script that downloads RSS feeds asynchronously and in parallel and searches them for the specified keywords. We followed the usual F# development style, so after introducing <a href="fsharp-webcast-functional.aspx">the basic functional concepts</a>, we wrote the code in <a href="fsharp-webcast-dotnet.aspx">the simples possible style</a> and demonstrated how to use <code>System.Xml</code> and <code>System.Net</code> namespaces. Then we <a href="fsharp-webcast-async.aspx">refactored the existing code</a>, to run asynchronously and process the results potentially in parallel, which was very easy thanks to F# <em>asynchronous workflows</em>.</p> <p>In this part of the series, we'll make the next evolutionary step of our sample application. We'll turn the code that originally used F# tuples and lists into code that uses standard .NET objects and we'll also see how to declare a class in F#. This simple modification will turn the script into an F# library that is almost indistinguishable from a library developed in C#. We'll also look how you can use the library from C# web application to show the interop between C# and F# in practice. We'll start with the code from the <a href="fsharp-webcast-async.aspx">previous part</a>, so if you missed that, you may want to check it out or download the source code.</p> F# Webcast (III.) - Using Asynchronous Workflows, 05 Jun 2009 03:39:39 GMTIn the previous part you've seen how to write a simple function for downloading RSS feeds and processing them. In this part, we look how to improve the function to download data asynchronously and process them potentially in parallel.Tomas Petricek<p>In this webcast, we'll look at improving the code for downloading and processing RSS feeds that I presented in <a href="fsharp-webcast-dotnet.aspx">the second part</a> (if you didn't see earlier parts, <a href="fsharp-webcast-dotnet.aspx">the first one</a> was an introduction to basic functional ideas). The previous part demonstrated how to use .NET libraries and we implemented a simple <code>downloadUrl</code> function for obtaining content of from the web and we've also seen how to load the data into an XML document object and how to filter items. In this part, we'll modify the code to run asynchronously and potentially in parallel. To use some of the functionality, you'll need to get <code>FSharp.PowerPack.dll</code>, which is available with the VS 2008 installation or as a separated download for VS 2010 [<a href="#fswc_asy">4</a>]. </p> <p>Now that we have the first version of the code, we can start <em>refactoring</em> it. I'm using the term in a slightly vague meaning - we're of course going to change the behavior of the code. We'll wrap it into F# <em>asynchronous workflow</em> to run without blocking threads and we'll also run multiple downloads in parallel. However, this can still be viewed as refactoring in some sense, because we're not changing the <em>core</em> behavior of the code. As you can see from the webcast, these kinds of refactorings are also very nicely supported by F# syntax...</p> F# Webcast (II.) - Using .NET libraries, 01 Jun 2009 14:57:53 GMTThis is the second part of the webcast series that introduces the F# language. It shows how to use .NET libraries from F# to download RSS feed and how to work with the obtained data using tuples, sequence expressions and other F# features.Tomas Petricek<p>About a week ago I posted <a href="fsharp-webcast-functional.aspx">the first part</a> of my F# webcast series. It focused on explainining the basic ideas behind functional programming such as immutability, recursion and passing functions as arguments to other functions (or methods in C#). In the first part, we've seen some C# code to demonstrate the ideas and also a bit of F#, mainly to show the basic language features. </p> <p>The second part is going to be exclusively about F#. It'll demonstrate how we can start writing a demo application that grabs data from RSS feeds and processes them. You'll learn how to access .NET libraries from F# (in particular, we'll use <code>System.Net</code> and <code>System.Xml</code>). We'll develop the code iteratively, which means that we'll start by simply enumerating the RSS elements using <code>for</code> loop and printing the results and then we'll refactor the code to use <em>tuples</em> and <em>sequence expressions</em> to turn it into processing code that generates a sequence of feed items. Finally we'll also demonstrate how to use some of the functions from the previous part such as <code>List.filter</code> in practice.</p>F# Webcast (I.) - Introducing functional concepts, 25 May 2009 13:39:54 GMTNow that Visual Studio 2010 beta 1 is out, it may be a good time finally try the new F# language. To make the exploration easier, I created a web cast series that demonstrates interesting aspects of F#. In this part, we'll look at basic functional concepts and working with data.Tomas Petricek<p>Now that <a href="" type="external">Visual Studio 2010 Beta 1</a> is out, it is finally a good time to take a look at one of the (in my opinion) most interesting new features in the new release - <a href="" type="external">the F# language</a>. F# existed for quite a long time now as Microsoft Research project, but is now becoming a real Microsoft product. Interestingly, F# is still available as a <a href=";FamilyID=7bb32f32-9fac-4f34-ad56-b0bda130cf00" type="external">plugin for Visual Studio 2008</a>, so if you want to try it you don't have to install the whole new beta of 2010.</p> <p>There are already many resources for learning F# including my <a href="">functional programming overview</a>, which is a Manning Greenpaper for the book <a href="" type="external">Functional Programming for the Real World</a> that I'm writing with Jon Skeet and my <a href="">four-part F# introduction</a>. There are also some useful links on the official <a href="">F# web site</a> including some talk recordings. However, I haven't yet seen any good F# webcast focusing mainly on showing F# source code, starting from simple functional concepts to the real-world features like asynchronous workflows and object-oriented programming in F#, so I decided to create one.</p> <p style="text-indent:0px;"><strong>So, here it is...</strong></p> Internship project: Reactive pattern matching, 17 May 2009 23:00:28 GMTI already mentioned that I was doing my second internship with Don Syme at MSR Cambridge. This time, I was in Cambridge for 6 months from October until April, so it has been more than a month since I left, but as you can guess I didn't have time to write anything about the internship until now...Tomas Petricek<a href=""> <img src="" alt="Cambridge, 2009" class="ldecor" style="border:0px;float:left; margin:20px" /> </a> <p>I already <a href="">mentioned</a> that I was doing my second internship with <a href="" type="external">Don Syme</a> at Microsoft Research in Cambridge. This time, I was in Cambridge for 6 months from October until April, so it has been more than a month since I left, but as you can guess I didn't have time to write anything about the internship until now... There isn't much to say though, because the internship was simply fantastic. Cambridge is a beautiful place (here are some <a href="" type="external">autumn</a> and <a href="" type="external">winter</a> photos), the Microsoft Research lab in Cambridge is full of smart people, so it is a perferct working environment (except that you realize that you're not as clever as you think :-)). Also, it is just a few meters away from the <a href="" type="external">Computer Laboratory</a> of the Cambridge University, so there are always many interesting talks and seminars. So, big thanks to Don Syme, James Margetson and everyone else who I had a chance to work with during the internship.</p> <p>One of the reasons why I didn't have much time to write about the internship earlier is that I was invited to the <a href="" type="external">Lang.NET Symposium</a> shortly after the end of the internship. I had a chance to talk about my project there as well and there is even a video recording from the talk (the link is below), so you can watch it to find out more about my recent F# work.</p> Imperative computation in F# (II.) - Writing break and continue, 25 Apr 2009 16:31:15 GMTIn the previous article of this series, we've implemented a computation expression that allows us to write imperative 'return' in F#. In this article, we'll add support for 'break' and 'continue'.Tomas Petricek<p>As I already wrote in the <a href="">first part of this series</a>, the F# language doesn't support some of the language constructs known from imperative languages such as C#. In particular, we cannot use imperative <code>return</code> statement that returns the result of a function from any place in the function code. In functional languages, every construct is an expression, so to get the overall result of the function, the F# language evaluates the expression and the value of the expression is used as the result. In the previous article, we've seen that we can simulate this construct in the F# language using F# computation expressions and I showed how to implement computation named <code>imperative</code> that allows us to write for example the <code>exists</code> function for working with sequences like this:</p> <pre lang="fsharp"> let exists f inp = imperative { for v in inp do if f(v) then return true return false } </pre> <p>In this article, we're going to look at two more imperative constructs and we're going to talk about <code>break</code> and <code>continue</code>. We'll see that we can quite easily extend the computation builder from the previous article to allow writing code that is syntactically very close to what you would write in C#. As I already mentioned, there are of course some performance overheads when using computation expressions, but I find it very interesting how nice imperative syntax we can get in functional F#:</p> <pre lang="fsharp"> imperative { for x in 1 .. 10 do if (x % 3 = 0) then do! continue printfn "number = %d" x } </pre> <p>The only difference between this code and the code we'd probably write if F# supported <code>continue</code> as a keyword is that we need to wrap the code inside the <code>imperative</code> computation and that we need to add the <code>do!</code> primitive before the <code>continue</code> value. Now that we've seen an example of using the <code>continue</code> value inside the imperative computations, let's look how we can extend the computation builder from the previous article to add this feature...</p> Imperative computation in F# (I.) - Returning results from a function, 19 Mar 2009 02:05:03 GMTEven though F# supports some imperative constructs such as for and while loops, it doesn't support some of the advanced constructs like imperative return and break. In this series, we'll look how we can implement these constructs ourselves using F# computation expressions.Tomas Petricek<p>One of the limitations of F# is that it doesn't very well support some of the advanced imperative language constructs such as <code>break</code>, <code>continue</code> or imperative style of returning value from a function, meaning that you can't write something like <code>return false</code> in the middle of the function. This has good reasons. F# doesn't in principle have the notion of <em>currently executing statement</em> and instead treat every code you write as an expression. Clearly, when there is no <em>current statement</em>, we cannot jump to other statements. If you're looking for more information about these basic principles, you can take a look at my book <a href="" target="external">Real World Functional Programming</a>, which covers this distinction in details in chapter 2, but we'll look at a brief example that will clarify this idea shortly.</p> <p>Often, there is really no need to use <code>break</code> or other imperative constructs in F#, because you can write the same thing more elegantly using one of the provided higher order function such as <code>Seq.exists</code> or <code>Seq.tryfind</code>. However, there are still some cases where the imperative programming style makes it easier to express our original intention. Also, implementing your own higher order functions (akin to <code>Seq.exists</code>) would sometimes be much easier if we could just use imperative return.</p> <p>So, what can be done about this?</p>Real World Functional Programming: Second review finished!, 02 Mar 2009 00:40:50 GMTI've been working on the <a href="" target="external">Real World Functional programming in .NET</a> book for quite some time now. In fact, I had the first discussions with Michael Stephens from Manning in March last year and I started thinking about the book at that time...Tomas Petricek<p>I've been working on the <a href="" target="external">Real World Functional Programming in .NET</a> book for quite some time now. In fact, I had the first discussions with Michael Stephens from Manning in March last year and I started thinking about the book at that time, so it has been occupying my mind for almost a year now! Until recently, I was feeling that we're not getting much closer to the end of this project, because writing a book is just <em>a lot</em> of work. However, I think I can finally see that we're getting closer to actually finishing the book. At Manning, we've recently finished the second review, which means that I've just got another set of very useful comments - a big thanks to all the reviewers! I'm also getting close to finishing the first draft of the whole manuscript (depending on the reviews, the content may still change a bit, but I expect to write at most one new chapter from now). Hopefully, the drafts will soon make it to the MEAP release of the book.</p> Source code for Real World Functional Programming available!, 12 Feb 2009 02:10:59 GMTJust a short update regarding the book I'm working on. First of all, the source code for the first 11 chapters is now available! Secondly, I did some changes to the TOC and you can now find the commented TOC on the book web site.Tomas Petricek<a href="" target="_blank"><img src="" class="ldecor" /></a> <p>As you can see, there has been quite a bit of silence on this blog for a while. There are two reasons for that - the first is that I'm still working on the book <a type="external" href="">Real World Functional Programming</a>, so all my writing activities are fully dedicated to the book. The second reason is that I'm having a great time doing an internship in the <a href="">Programming Principles and Tools</a> group at Microsoft Research in Cambridge with the F# team and namely the F# language designer <a href="" type="external">Don Syme</a>. The photo on the left side is the entrance gate to the Trinity College of the Cambridge University taken during the few days when there was a snow. I recently started using Live Gallery, so you can find more photos from Cambridge in my <a href="" type="external">online gallery</a>. Anyway, I just wanted to post a quick update with some information (and downloads!) related to the book... </p> Functional Programming in .NET using C# and F# (Manning Greenpaper), 11 Dec 2008 01:48:07 GMTThis article is partially an excerpt from my <a href="">book</a>. It introduces the benefits of functional pogramming, and explains the essential aspects of the functional style using F# and C# 3.0. Finally, it also shows how functional style influences the application architecture.Tomas Petricek<p> Functional programming languages have been around for a while and were always astonishing for their ability to express the ideas in a succinct, declarative way allowing the developer to focus on the essence of problem rather than on technical details of the solution. Recently, functional paradigm is gaining new prominence as an efficient way to handle development of multi-processor, parallel and asynchronous applications.</p> <p> Functional ideas are arising in C# as well as in other main-stream languages and functional languages are becoming an alternative for real-world projects. Also, Microsoft recently introduced a new language called F#, which has a strong background in traditional functional languages, but as a .NET language also benefits from the rich .NET and Visual Studio ecosystem.</p> <div class="rdecor"> <img src="" alt="Book cover" /><br /><small>Available via MEAP | 500 pages<br />Softbound print: March 2009 (est.)</small></div> <p> This article is partially an excerpt from my book <strong><a href="">Real-world Functional Programming in .NET</a></strong> [<a href="#fpgpref">1</a>]. Thanks to my editors at <a href="" type="external">Manning</a> I have the permission to publish it on my blog. We’ll look at several aspects of functional programming and how the same concepts, which are essential for the functional paradigm, look in the F# and in C# 3.0 with LINQ. We will shortly look at the basic programming language features like lambda functions and type inference that are now available in both F# and C#. Functional programming isn’t only about language features, but also about using different programming style, so we’ll look at some high level concepts as well. These include using immutable data structures for developing code that can be executed in parallel and writing code in a more declarative style.</p> <p> Thanks to the combination of C# 3.0 and F#, this article shows the ideas in a way that should be familiar to you in C#, but also shows a further step that you can take with a primarilly functional language F#. If you're a .NET developer and you want to understand what functional programming is and how it can help you to become better and more productive then continue reading. If you'll find this article interesting, then don't forget to check out the <a href="">book</a>, which explains everything in larger detail and discusses many other interesting ideas.</p> Reactive Programming (IV.) - Developing a game in Reactive LINQ, 24 Nov 2008 03:00:00 GMTIn this article, we'll implement a simple iteractve game using the <strong>Reactive LINQ</strong> project. The article shows that this way of handling events gives us amog other things a great degree of composability.Tomas Petricek<p>In this part of the article series about <strong>Reactive LINQ</strong>we're going to implement a slightly more complicated application using the library that I introduced in the previous three articles. We're going to use basic event stream queries from the <a href="reactive-ii-csevents.aspx">second article</a> as well as advanced operators introduced in the <a href="reactive-iii-linqoperators.aspx">third part</a>. This time, I'll also show the F# version of all the examples, so we're going to build on the ideas from the <a href="reactive-i-fsevents.aspx">first part</a>.</p> <p>I originally wanted to write the demo only in Visual Basic, because I think that it is really amazig to show an idea that came from functional programming in a language that no one (maybe until recently) connects with functional programming. Then I realized that I really want to show the F# version too, because F# was an inspiration for the whole <strong>Reactive LINQ</strong> idea and it is interesting alone as well. But finally, I thought that don't showing the C# version may look offensive to many readers (especially since I'm still C# MVP...). So, I ended up writing the game in all three languages, but the code is surprisingly similar in all of them!</p> Reactive Programming (III.) - Useful Reactive LINQ Operators, 21 Nov 2008 19:59:02 GMTIn the previous article, I introduced <strong>Reactive LINQ</strong>. Today, we're going to look at other operators that canbe used for working with events. We'll see aggregation is useful and how to dynamically change (switch) behavior.Tomas Petricek<p>In the <a href="reactive-ii-csevents.aspx">previous article</a>, I introduced <strong>Reactive LINQ</strong>. I explained the different point of view that we can use when working with .NET events. The idea is that .NET events can be viewed as streams of values. The value is information about the event (such as position of a mouse click or a mouse movement). These streams can be processed using LINQ queries - we can for example filter all values that are not interesting for us using <code>where</code> LINQ clause. For example if we want to handle clicks only in some specified area.</p> <p>In the previous article, I talked about basic LINQ query operators such as <code>select</code> and <code>where</code> and some useful methods that <strong>Reactive LINQ</strong> provides (for example for merging event streams). Today, we'll take a look at two more advanced kinds of operations that we can use for working with event streams. In particular, we'll talk about aggregation operators (that you certainly know from LINQ) and about switching. Switching is a concept from functional reactive programming and it allows us to change dynamically how the application behaves. However, I'll explain this in a more detail soon.</p> <p>In this article, I'm going to use mostly C# (and some Visual Basic). The functionality that I'm describing in this part isn't part of the standard F# <code>Event</code> module that I discussed in <a href="reactive-i-fsevents.aspx">the first part</a>. I implemented most of them in F# too, but I'm not going to write the samples in both of the versions in this part. If you've seen the first two articles, you'll be definitely able to use the F# versions as well, because they follow exactly the same ideas as the C#/LINQ versions. I'm going to talk about a larger demo application in the last section and I'll show an F# version as well, so you'll see some F# examples in the next part. This part serves more as a reference of the available operators, so you may read only some parts of it, then jump to the last one (to see an exciting example!) and then come back here.</p> Reactive programming (II.) - Introducing Reactive LINQ, 19 Nov 2008 19:57:15 GMTIn the second part of the series about reactive programming, I introduction the <strong>Reactive LINQ</strong> project, which allows writing event processing code in C# using LINQ queries.Tomas Petricek<p>In this article I'm going to introduce my project <strong>Reactive LINQ</strong>. This is largely inspired by the ideas that come from functional reactive programming in the Haskell language and from functionality that's available for working in events in F#. I introduced these ideas in my previous article in this mini-series, so if you're interested in learning more about these interesting technologies, you should definitely read the previous article about <a href="reactive-i-fsevents.aspx">First class events in F#</a>.</p> <p>In this article, we're going to look how to apply the same ideas to the C# language and how to use LINQ queries for processing events. This article is <a href="">just</a> <a href="">another</a> my article that shows how to implement some idea from functional programmin in C#. I believe this will once again show that the new features in the C# 3.0 aren't just about querying databases, but are more widely useful even in situations that are not directly related to data-processing. </p> Reactive programming (I.) - First class events in F#, 16 Nov 2008 17:14:04 GMTThe LINQ project and changes in C# 3.0 are interesting because they allow implementing many ideas from functional languages in C#. In this article I'll explain "first-class events" in F# and later I'll implemet similar concept using LINQ.Tomas Petricek<p>I believe that the LINQ project and changes in C# 3.0 and VB 9 are interesting because they allow rewriting of many ideas from functional programming. An ability to express queries easily is one of these ideas, but it is definitely not the only one. There are many other interesting ideas. The C# 3.0 language isn't primary a functional language, so it isn't easy to discover the idea if you use only C#, but it is possible to implement it if you know the idea already.</p> <p>I already wrote a few interesting C# examples that were inspired by some functional idea. I'm a big fan of the F# language, so it is not a surprise that I started with an F# version of the problem and then looked at the way to do the same thing in C#. In particular, this is how my article about building dynamic queries in C# came to the existence - the F# version used <a href="">FLINQ and Quotations</a> and then I demonstrated how to do the same in <a href="">C# using expression trees</a>. Another example is my article about asynchronous programming in C# <a href="">using iterators</a>, which shows how to implement something like F# <a href="">asynchronous workflows using iterators</a> in C# 2.0.</p> <h3>Functional Reactive Programming</h3> <p>Today, I'm going to look at another very interesting idea from functional programming. It is called <em>Functional Reactive Programming</em> and it comes from the Haskell community. You can find a list of related <a href="" type="external">Haskell projects here</a>. However, similar things (though they are not purely functional and simplified) are available in the F# language as well. Don Syme introduced them in his blog post called <a href="">F# First Class Events: Simplicity and Compositionality in Imperative Reactive Programming</a>. In this article, I'm going to briefly introduce the implementation available in F# and I'll extend it a little bit to allow some more interesting things. In the second article from this series, I'll show how to implement the same thing in C# 3.0 (and in VB 9 too!)</p> Calculating with infinite sequences on MSDN, 13 Nov 2008 02:36:30 GMTAbout a year ago, I wrote an article about infinite sequences on MSDN. I remembered about it this week, because these topics will be discussed in the book I'm working on as well...Tomas Petricek<p>About a year ago, I wrote <a href="">an article</a> about using lazy computations in C# 3.0. It was published by the C# Community PM <a href="" type="external">Charlie Calvert</a> at the C# Developer Center. The article was a first of two articles where I wanted to demonstrate that C# 3.0 can be used for implementing useful constructs known from functional languages. I realized that I never posted the link to the second article to my blog, so you can find the annotation and link below.</p> <p>However, I remembered about these two articles because I was just working on chapters 11 and 12 of the <a href="">Real-world Functional Programming in .NET</a> book that I’m writing. Lazy values, which were the topic of my first article, are discussed in the second part of chapter 11 and IEnumerable and F# sequences are the topic for the first part of chapter 12. Because I already wrote two articles on this topic, I had to think really hard to find better (and still simple enough) examples where these concepts are useful in practice. I also finally have enough space to show how these two concepts relate and talk about some interesting background – for example in Haskell, lazy sequences are in fact just ordinary lists that are lazy thanks to the Haskell nature. </p> <p>A year ago, I definitely wouldn’t believe that today, I’ll be writing about the same topics, but this time as part of a book that has partly the same goal as these two articles – to show that functional programming ideas are really useful in the real-world and can enrich your programming toolbox (no matter whether you’re using C# or F# language). Anyway, here is the link to the second article – as usual when I look at something that I worked on a long time ago, I think I should rewrite it to make it better :-), but it still gives you an idea what is the book that I’m working on about...</p>Functional Programming in .NET book - An update, 20 Oct 2008 22:10:04 GMTRecently, I announced on my blog that I’m working on a book for Manning called Real-world Functional Programming in .NET. It is more than a month since I wrote about it, so here is a brief update...Tomas Petricek<p>Recently, I announced on my blog that I’m working on a book for <a href="" type="external">Manning</a> called <em>Real world Functional Programming in .NET</em>. The goal of the book is to explain the most interesting and useful ideas of functional programming to a real world C# developer. I'm writing this book, because I believe that functional programming is becoming increasingly important. Here is a couple of reasons why you should have this book on your bookshelf:</p> <ul> <li><strong>Ideas behind C# 3.0 and LINQ</strong> - these main-stream technologies are inspired by functional programming and the new C# 3.0 features give us definitely much more than just a new way to query databases. The book explains the ideas behind these features and shows how to use them more efficiently.</li> <li><strong>Learning the F# language</strong> - <a href="" type="external">F# is becoming a first-class citizen</a> in the Visual Studio family of languages, which alone would be a good reason for learning it! Even if you're not going to use it for your next large .NET project, you'll find it useful for quick prototyping of ideas and testing how .NET libraries work thanks to the great interactive tools. </li> <li><strong>Real world examples</strong> - the book includes a large set of real-world examples that show how to develop real applications in a functional way - both in F# and C#. Among other things, the examples show how to utilize multi-core CPUs, how to better obtain and process data and how to implement animations and GUI applications in a functional way.</li> </ul> <p>The book is available via the MEAP (Manning Early Access Program) and if you want to get a better idea what is the book about, you can read the <a href="" type="external">first chapter for free</a>. Anyway, it is more than a month since I <a href="">posted the announcement</a>, so I decided to write a brief update....</p>Announcing: Real-world Functional Programming in .NET, 02 Sep 2008 20:03:15 GMTIf you’ve been reading my blog or seen some my articles, you know that I’m a big fan of the F# language and functional programming style. Today, I'm very pleased to announce that I'm writing a book on this topic!Tomas Petricek<p>If you’ve been reading my blog or seen some my articles, you know that I’m a big fan of the F# language and functional programming style. I’m also often trying to present a bit different view of C# and LINQ – for me it is interesting mainly because it brings many functional features to a main-stream language and allows using of many of the functional patterns in a real-world. Elegant way for working with data, which is the most commonly used feature of C# 3.0, is just one example of this functional approach. Talking about real-world applications of functional programming, there is also fantastic news about F#. It was announced last year that F# will become fully supported Visual Studio language and the first CTP version of F# was released this week!</p> <p>I always thought that the topics mentioned in the previous paragraph are really interesting and that functional programming will continue to become more and more important. That’s why I’m really excited by the news that I’d like to announce today – I’m writing a book about functional programming in F# and C#....</p>Dynamic Lookup in F#, 04 Jun 2008 01:50:08 GMTDynamic languages allow you to represent a member using a symbol or a string and to use this symbol to work with the member. In this article I'll show how to do same thing in statically-typed way in F#.Tomas Petricek<p>Many people view <em>dynamic</em> and <em>statically-typed</em> languages as two distinct groups (and this is often a reason for never-ending discussions). In this article, I'll try to show one interesting example, which demonstrates that these two groups are not in fact that distinct and that you can implement a common <em>dynamic</em> language feature in F#, which is undoubtedly <em>statically-typed</em>. The feature that I'm talking about is dynamic invoke using a symbolic representation of the member (this is something that can be done using <em>symbols</em> in Ruby, but I'll shortly explain what exactly I mean).</p> <p>I intentionally wrote <em>statically-typed</em> and <em>dynamic</em> instead of <em>dynamically-typed</em>. In my understanding <em>dynamic</em> is a broader term while <em>dynamically-typed</em> and <em>statically-typed</em> are of course two distinct groups. On the other side <em>dynamic</em> refers to language features that are usually available in <em>dynamically-typed</em> languages, just because it is easy to support them in a nice way. This doesn't mean that having a <em>dynamic</em> feature in a <em>statically-typed</em> language would be impossible - it is just more difficult to implement it in a way that would be similarly elegant. </p> Thesis: Client-side Scripting using Meta-programming, 17 Mar 2008 10:07:04 GMTContains a link to my Bachelor Thesis about F# WebTools, which I partially worked on during my visit in Microsoft Research and which I successfully defended last year.Tomas Petricek<p>I realized that I haven’t yet posted a link to my Bachelor Thesis, which I partially worked on during my visit in Microsoft Research and which I successfully defended last year. The thesis is about a client/server web framework for F# called F# WebTools, which I already <a href="" type="external">mentioned here</a> and its abstract is following:</p> <p style="padding-left:40px;padding-right:40px;font-style:italic;">“Ajax” programming is becoming a de-facto standard for certain types of web applications, but unfortunately developing this kind of application is a difficult task. Developers have to deal with problems like a language impedance mismatch, limited execution runtime in web browser on the client-side and no integration between client and server-side parts that are developed as a two independent applications, but typically form a single and homogenous application. In this work we present the first project that deals with all three mentioned problems but which still integrates with existing web technologies such as ASP.NET on the server and JavaScript on the client. We use the F# language for writing both client and server-side part of the web application, which makes it possible to develop client-side code in a type-safe programming language using a subset of the F# library, and we provide a way to write both server-side and client-side code as a part of single homogeneous type defining the web page logic. The code is executed heterogeneously, part as JavaScript on the client, and part as native code on the server. Finally we use monadic syntax for the separation of client and server-side code, tracking this separation through the F# type system.</p> <p style="text-indent:0px">The full text is available here: <a href="/articles/webtools-thesis/fswebtools.pdf">Client side scripting using meta-programming</a> (PDF, 1.31MB) </p>New Version of Phalanger with Silverlight and VS 2008 Support, 11 Mar 2008 01:14:21 GMTThis article introduces new version of the Phalanger project, which incudes support for Silverlight 1.1 (alpha) and Visual Studio 2008 Integration package.Tomas Petricek<p>At the <a href="" type="external">Lang.NET Symposium</a> I presented several new features in Phalanger. I already posted the presentation and samples on the blog (<a href="" type="external">here</a>) and the talk is also available as a video on the Lang.NET web site (<a href="" type="external">here</a> - actually, due to the huge demand the site is down now, but I hope it gets back soon!) Anyway, the most interesting thing is that I've used Phalanger Integration for <strong>Visual Studio 2008</strong> during the talk, which wasn't available in any Phalanger release until now.</p> <p>I have to mention one more thing before talking more about the new release - Phalanger Integration for VS 2008 works with Visual Studio Shell, which means that you can get <strong>Visual Studio 2008 with Phalanger Support for free!</strong> Yes, that's right. Microsoft offers so called Visual Studio 2008 Shell, which is an "empty" IDE with no integrated languages and you can install Phalanger Integration into this version, which means that you can get very good Phalanger IDE (for Windows) for no cost at all!</p> <p>If you can't wait to install this new version, you can skip the overview article and <a href="/blog/phalanger-vs2008.aspx#phpm08down">go directly to the installation links</a>.</p> F# Support for ASP.NET and Notes on Samples, 08 Mar 2008 23:07:29 GMTIn this article I look at the F# suppot for ASP.NET and at some interesting aspects of the samples that are available in the F# distribution.Tomas Petricek<p>As I mentioned earlier, I spent three months as an intern in Microsoft Research in Cambridge last year and I was working with Don Syme and James Margetson from the F# team. Most of the time I was working on the F# Web Toolkit, which I introduced on the blog some time ago [<a href="#myfsstuff">1</a>], but I also worked on a few additions that are now part of the F# release. Probably the most useful addition is a new implementation of the CodeDOM provider for the F# language which makes it possible to use ASP.NET smoothly from F# (but it can be used in some other scenarios as well) together with two ASP.NET sample applications that you can explore and use as a basis for your web sites. This was actually a part of the distribution for a few months now (I of course wanted to write this article much earlier...), so you may have already noticed, but anyway, I'd still like to write down a short description of these ASP.NET samples and also a few tips for those who're interested in writing web applications in F#. </p> Phalanger at Lang.NET Symposium, 02 Feb 2008 11:51:38 GMTLast week I attended the Lang.NET Symposium and I also did a short presentation about Phalanger. The slides and demos from the talk are attached.Tomas Petricek<p>Last week I attended the <a href="" type="external">Lang.NET Symposium</a> and I also did a short presentation about Phalanger (below you can find the demos and slides from my talk). By the way – during the trip from Prague to Seattle I missed a connecting flight from Paris, so I had one day to visit Paris and since I was traveling on Saturday I actually quite enjoyed it :-), so that’s where the picture comes from.</p> <p>Overall it was really a fantastic event with many great talks from many interesting people. I hope that there will be recordings as a last year, so I won’t comment every topic that I found interesting (that would be really a long post). But just quickly – people from Microsoft often talked about DLR (dynamic language runtime) related topics, which was interesting as we’re planning to look at DLR in Phalanger. Luckily, <a href="" type="external">Wez Furlong</a> from the PHP community was there too, so we discussed how we could work on “PHP on DLR” project together (see also our <a href="" type="external">mailing list</a>).</p> <a target="_blank" href="/articles/phalanger-at-langnet/photo.jpg"><img style="float:right;margin:10px;border:0px" alt="Trip to Seattle" src="/articles/phalanger-at-langnet/photo_sm.jpg" /></a> <p>There were also two talks about F# (from <a type="external" href="">Luke Hoban</a> and <a href="" type="external">Harry Pierson</a>), and it was a lot of fun to hang out with them. Finally, Erik Meijer presented the <a href="" type="external">Volta</a> project, which I was particularly interested in as it shares many goals and ideas with my F# Web Tools.</p> <p>Non-Microsoft talks covered wider range of topics including Mono and Moonlight project (by <a href="" type="external">Miguel de Icaza</a>) and I actually had a chance to talk with Miguel about Phalanger and we even tried running the Helicopter sample on Moonlight – there were some issues, but it seems quite promising, so I hope to have the sample running on Moonlight on Linux quite soon! Miguel mentioned that the installation of Moonlight is currently a bit painful (due to some issues with media codecs), but it should be fixed in next few weeks, so I hope to be able to try it on my machine too!</p>Writing Silverlight applications in PHP, 07 Dec 2007 17:16:14 GMTIn this article we will look how Phalanger can be used for developing Silverlight applications in the PHP language. We look at basic concepts like XAML as well as at a more complicated game.Tomas Petricek<p>In my <a href="">last post</a> about Phalanger I mentioned that our important goal is to support the Silverlight (2.0) platform. Shortly Silverlight is a cross-browser platform that can be used for developing client-side components that run in the web browser and contain rich media, graphics and can interactively communicate with the user. The language that can be used for writing Silverlight code can be in general any .NET language, so our goal is to allow using PHP by making Phalanger compatible with Silverlight.</p> <img src="/articles/php-in-silverlight/car_intro_sm.png" alt="Simple Silverlight App in PHP" style="margin:10px; float:left;" /> <p>First steps were already made and it is becoming possible to write some very interesting things in Silverlight using PHP, there is of course still a lot of work to do and we're discussing the future development with PHP development team (you can join the mailing list <a href="" type="external">PHP on DLR</a> for more info). In this article we will first show a very basic Silverlight example that uses PHP and later I will shortly comment more complicated example - a game (quite addicting, so be careful :-)!) where you have to fly with helicopter and avoid the walls. The source code for helicopter game is also attached, so feel free to modify it or create similar games!</p> <p>If you can't wait to try the demos before looking at the sources, here are the links:</p> <ul> <li><a href="" type="external">Simple car demo</a> - Click on the car and it will move!</li> <li><a href="" type="external">Helicopter game demo</a> - Click left button to fly up!</li> </ul>A few notes about Phalanger future, 02 Dec 2007 23:50:53 GMTThis post discusses Phalanger future and relations to the DLR and Silverlight as well as our intention to closely communicate wth the PHP community.Tomas Petricek<p>First, I'd like to aplogoize for the lack of new about the Phalanger project recently. I spent some time working as an intern with the F# team in MSR Cambridge and I also had final bachelor exam this autumn. Anyway, this doesn't mean that there isn't anything new and interesting regarding the Phalanger project comming soon - actually (as I believe) the opposite is true! The topics that I'm going to further discuss in this article is our upcomming support for Silverlight platform, the relation between Phalanger and DLR and also our desire to make Phalanger more open to the community, so stay tuned!</p> Infinite Cheese Fractal using WPF 3D and F#, 24 Nov 2007 23:22:04 GMTThis article describes a 3D version of famous Sierpinski carpet fractal implemented in the F# language using WPF 3D libraries from .NET 3.0.Tomas Petricek<p>I always liked fractals, because they look like objects from another world, but on the other side if you look at some things in our world you can see many similarities with fractals (but not quite as ideal with the infinite level of precision). One of my favorite fractals is 3D version of Sierpinski carpet [<a href="#wpffractref">1</a>], which itself is based on very famous Cantor set. Quite long time ago I thought that it would be nice to implement animation of flying through this fractal, but I was never good in 3D graphics and it looked like a lot of work, so I never get to doing it. Luckily, now with F#, which makes it very easy to write the code to generate the fractal and with WPF 3D, which can be easily used to animate the fractal, I finally had everything I needed to do it, so here it is! </p> <div style="text-align:center;"> <object width="425" height="344"><param name="movie" value=";hl=en&amp;fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src=";hl=en&amp;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object> </div> Asynchronous Programming in C# using Iterators, 15 Nov 2007 03:08:35 GMTIn this article we will look how to write programs that perform asynchronous operations like manipulation with network in C# using iterators without the typical inversion of control caused by the use of delegates.Tomas Petricek<p>In this article we will look how to write programs that perform asynchronous operations without the typical inversion of control. To briefly introduce what I mean by 'asynchronous' and 'inversion of control' - asynchronous refers to programs that perform some long running operations that don't necessary block a calling thread, for example accessing the network, calling web services or performing any other I/O operation in general. The inversion of control refers to the code structure that you have to use when writing a code that explicitly passes a C# delegate as a callback to the asynchronous method (typically called <code>Begin<em>Something</em></code> in .NET). The asynchronous method calls the delegate when the operation completes, which reverses the way you write the code - instead of encoding the control flow using typical language constructs (e.g. <code>while</code> loop) you have to use global variables and write your own control mechanism.</p> <p>The funny thing about this article is that it could have been written at least 3 years ago when a beta version of Visual Studio 2005 and C# 2.0 became first available, but it is using iterators in a slightly bizarre way, so it is not easy to realize that this is possible. Actually, I will use some C# 3.0 methods in the article as well, but only extension methods and mainly just to keep the code nicer. As with my earlier article about building LINQ queries at runtime, I realized that it can be done in C# when I was playing with the F# solution (called F# Asynchronous Workflows), where this approach is very natural, so I will shortly mention the F# implementation as well.</p> F# Overview (IV.) - Language Oriented Programming, 03 Nov 2007 00:00:04 GMTIn the fourth article of the F# overview series, I will shortly describe how I understad the language oriented paradigm and how the F# language can be used for developing libraries using this paradigm.Tomas Petricek<p>In the fourth article of the F# overview series, I will shortly describe how I understad the language oriented paradigm and how the F# language can be used for developing libraries using this paradigm. We will look how discriminated unions relate to this paradigm and at three specific features that support this paradigm, namely <em>active patterns</em>, <em>computation expressions</em> and <em>quotations</em>.</p> <p>Defining precisely what the term <em>language oriented programming</em> means in context of the F# language would be difficult, so I will instead explain a few examples that will demonstrate how I understand it. In general, the goal of language oriented programming is to develop a <em>language</em> that would be suitable for some (more specific) class of tasks and use this language for solving these tasks. Of course, developing a real programming language is extremely complex problem, so there are several ways for making it easier. As the most elementary example, you can look at XML files (with certain schema) as language that are processed by your program and solve some specific problem (for example configuring the application). As a side note, I should mention that I'm not particularly happy with the term ‘language’ in this context, because the term can be used for describing a wide range of techniques from very trivial constructs to a complex object-oriented class libraries, but I have not seen any better term for the class of techniques that I’m going to talk about.</p>F# Overview (III.) - Imperative and Object-Oriented Programming, 03 Nov 2007 00:00:03 GMTIn the third part of the F# overview, we will look at the F# features that are essential for a smooth interoperability with other .NET languages and form a second part of the F# core language - that is object oriented and imperative programming.Tomas Petricek<p>In the third part of the F# Overview article series, we will look at language features that are mostly well known, because they are present in most of the currently used programming languages. Indeed, I'm talking about imperative programming, which is a common way for storing and manipulating application data and about object oriented programming which is used for structuring complex programs.</p> <p>In general, F# tries to make using them together with the functional constructs described in the <a href="fsharp-ii-functional.aspx">previous part</a> [<a href="fsharp-ii-functional.aspx" target="_blank">^</a>] as natural as possible, which yields several very powerful language constructs.</p>F# Overview (II.) - Functional Programming, 03 Nov 2007 00:00:02 GMTIn the second part of the F# overview we will look at functional programming, which is probably the most important paradigm used with the F# language, because F# is built on the same grounds as many functional languages.Tomas Petricek<p>In the second part of the F# overview we will look at functional programming, which is probably the most important paradigm used with the F# language, because F# is built on the same grounds as many functional languages. We will first examine the standard F# data types, which are useful to allow the functional programming style and we will also look at a few functional tricks.</p> <p>As already mentioned in the <a href="fsharp-i-introduction.aspx">Introduction</a> for this article series, F# is a typed functional language, by which I mean that types of all values are determined during the compile-time. However, thanks to the use of a type inference, the types are explicitly specified in the code very rarely as we will see in the following examples. Basic data types (aside from a standard set of primitive numeric and textual types that are present in any .NET language) available in F# are tuple, discriminated union, record, array, list, function and object. In the following quick overview, we will use the F# interactive, which is a tool that compiles and executes the entered text on the fly.</p> F# Overview (I.) - Introduction, 03 Nov 2007 00:00:01 GMTFirst article of the F# Overview series introduces the F# language and gives a quick overview of the programming paradigms that will be discussed in the upcoming articles.Tomas Petricek<p>In my bachelor thesis I included a short introduction that covered all of the important aspects of the F# programming language and I thought that it may be useful to extend it a little bit to cover also a topics that were not important for my thesis and post it as an article, so there is one and relatively short article that introduces all the interesting F# features. The article got however a bit longer than I expected, so I decided to split it into a three parts that would introduce three different <em>paradigms</em> that are supported by F#. Of course, this series won't teach you everything about F#, but it tries to cover the main F# design goals and (hopefully) presents all the features that make F# interesting and worth learning. In this first part I will shortly introduce F# and the supported paradigms that will be discussed in the upcoming articles.</p> Lazy Computation in C# on MSDN, 06 Oct 2007 01:29:59 GMTI think that one of the interesting things about C# 3.0 is that it gives you the ability to use many techniques known from functional languages...Tomas Petricek<p>I think that one of the interesting things about C# 3.0 is that it gives you the ability to use many techniques known from functional languages (like Haskell or F#). Most of the articles about C# 3.0 and LINQ focus on the queries and LINQ to SQL, but I believe that using these functional techniques deserve some attention as well. This is why I'm very happy that my article about one of these techniques - representing lazy computations - is now available at the C# Developer Center. I would like to thank to <a href="">Charlie Calvert</a> [<a href="" target="_blank">^</a>], who is the Community Program Manager for C# and who edited and published my article there. Here is the annotation:</p> <p style="padding-left:40px;padding-right:40px;font-style:italic;">Most of the programming languages used in practice (including for example C#, VB.NET, C++, Python or Java) employ so called eager evaluation, which means that the program evaluates all expression and statements in the order in which they are written, so all the preceding statements and expressions are evaluated before executing the next piece of code. This, for example, means that all arguments to a method call are evaluated before calling the method. Sometimes it may be useful to delay an execution of some code until the result is actually needed, either because the result may not be needed at all (but we can’t tell that before executing some computation) or because we don’t want to block the program for a long time by executing all computations in advance and instead we want to execute the computations later, when we will actually need the result. </p> <p style="padding-left:40px;margin-bottom:20px;padding-right:40px;font-style:italic;">In this article we will look how these lazy computations can be written in C# (using some of the new language features from version 3.0). We will first implement a Lazy class to represent this kind of computation, then look at a few simple examples to demonstrate how the class can be used, and finally we will examine one slightly more complicated, but practically useful application. </p> <p style="text-indent:0px">You can read the complete article here: <a href="">Lazy Computation in C# </a> [<a href="" target="_blank">^</a>]</p>F# Quotations Samples on CodePlex, 20 Sep 2007 04:33:49 GMTThis article describes a few samples available in the F# Samples project at CodePlex that demonstrate how to work with the F# quotations using active patterns.Tomas Petricek<p>Some time ago, Granville Barnett (see his <a href="">homepage and old blog</a> [<a href="" target="_blank">^</a>] or a <a href="">new blog</a> [<a href="" target="_blank">^</a>]) had a great idea and started a CodePlex project called <a href="">F# Samples</a> [<a href="" target="_blank">^</a>] to host various samples written in F# to demonstrate the most important concepts of both functional programming and F#. I quite like this idea, so I asked Granville if I could join and add some samples that I wrote and today I finally found a time to update what I wanted to upload to the latest version of F# and put it online.</p> Building LINQ Queries at Runtime in F#, 18 Aug 2007 02:38:11 GMTIn this article I will introduce FLinq, the F# support for language integrated query and show how we can construct a database queries dynamically in a type-safe way in F#.Tomas Petricek<p>In an article about building LINQ queries at runtime in C# 3.0, I described how you can build a LINQ query dynamically, for example by combining a set of conditions using the 'or' operator in the where clause. I mentioned that the way I implemented it is largely influenced by the F# language, which provides very natural way for manipulations with code like this. In this article I will first shortly introduce FLINQ sample, which is an F# library implementing LINQ support and than I will implement the same examples I presented in the earlier article in F#.</p> Building LINQ Queries at Runtime in C#, 30 Jul 2007 02:10:17 GMTCommon criticism of LINQ is that it doesn't support a scenario where queries are build dynamically at the runtime. In this article I show that this can be acutally done very well for most of the common scenarios.Tomas Petricek<p>Since the first beta versions of LINQ we could hear comments that it is perfect for queries known at compile-time, however it is not possible to use it for building queries dynamically at runtime. In this article I show that this can be actually done very well for most of the common cases. The solution offered by Microsoft (mentioned in [<a href="#dynqlinks">1</a>]) is to build query from a string, however this has many limitations and it in fact goes completely against what LINQ tries to achieve, which is writing queries in a type-safe way with full compile-time checking. In this article I will first show a few support functions to make the life a bit easier and then we will use them for building two sample applications that allows user to build a query dynamically. The solution is largely motivated by my previous use of F#, where working with “expressions” is possible at more advanced level, however I’ll write about F# later and now let’s get back to C# 3.0...</p>F# Web Tools: "Ajax" applications made simple, 13 Jul 2007 04:32:29 GMTThis article introduces the F# Web Toolkit, which is an "Ajax" web framework that solves three major problems that many people have to face when developing modern web applications.Tomas Petricek<p>Traditional "Ajax" application consists of the server-side code and the client-side part written in JavaScript (the more dynamicity you want, the larger JS files you have to write), which exchanges some data with the server-side code using XmlHttpRequest, typically in JSON format. I think this approach has 3 main problems, which we tried to solve in F# Web Toolkit. There are a few projects that try to solve some of them already - the most interesting projects are Volta from Microsoft [<a href="#fswtintrolinks">1</a>], Links language [<a href="#fswtintrolinks">3</a>] from the University of Edinburgh and Google Web Toolkit [<a href="#fswtintrolinks">2</a>], but none of the projects solve all three problems at once. </p> <ol> <li>Limited client-side environment</li> <li>Discontinuity between server and client side</li> <li>Components in web frameworks are only server-side</li> </ol> <p>The aim of the F# Web Toolkit is to solve all these three problems...</p>Using PHP objects from C# in a type-safe way, 30 Apr 2007 01:26:24 GMTIn this article we present new features in the Phalanger beta 4 which make it possible to use objects from any PHP script in C# using type-safe way.Tomas Petricek<p>When you want to call PHP scripts from mainstream .NET languages, like C# you can follow two different ways. First you can use the pure mode as I demonstrated in one of the earlier articles on PHP application called Texy!. This approach can be used only for some specific applications, because pure mode has several restrictions - the two most important restrictions are that no global code or inclusions are allowed (you have to specify all source files during the compilation), but thanks to this restrictions Phalanger is able to produce classes that are compatible with .NET and can be called from C#. Second option is to create object dynamically by its name and perform all method invocations by name too. This approach can be used with any PHP scripts, but it isn't very convenient. In this article we present new features in the Phalanger beta 4 which extend the second approach and make it possible to use objects from any PHP script in C# using type-safe way.</p> Phalanger 2.0 Beta 4 available!, 22 Apr 2007 16:24:09 GMTThis week we finished new release of the Phalanger project, what PHP applications are supported and what new features are available in this release?Tomas Petricek<p>This week we finished new release of Phalanger (the PHP compiler for .NET platform). The goal in this release was to fix many minor bugs preventing us from running some of the famous and most often deployed open-source PHP applications, so with the new release you'll be able to run for example <strong>MediaWiki</strong>, the wiki application that evolved from system used on Wikipedia or probably the best-known PHP blogging and publishing system <strong>WordPress</strong>. Other applications that we tested can be found at Phalanger website in <a href="">the list of tested PHP applications</a> [<a href="" target="_blank">^</a>]. Compatibility is very important for us, so if you have troubles running any open-source PHP application, let us know and we'll include it in our list!</p> <p>Another thing that we focused on is interoperability between PHP scripts compiled using Phalanger and other .NET languages. Using .NET objects from Phalanger is very intuitive and has almost no limitations, however the other way is a bit difficult because of the dynamic nature of PHP language. If your PHP application can be compiled in the Phalanger <strong>pure</strong> mode, than the PHP objects can be exported and made available to C# and other languages. The methods of objects exported using this method take <code>object</code> (the base class for every .NET object) as a parameter, because PHP checks types at runtime, so this may be a bit confusing for the users. In the Beta 4 we tried to target these two issues - first, the fact that you have to use pure mode and second, the fact that exported objects can't contain any information about accepted types. This is a topic for entire article, so I'll write about it soon... Stay tuned :-)!</p> <p>Here are the links for Phalanger 2.0 Beta 4 release:</p> <ul> <li><a href=""> Phalanger 2.0 Beta 4 release page</a> [<a href="" target="_blank">^</a>] - CodePlex</li> <li><a href=""> Phalanger MySQL extension Beta 4</a> [<a href="" target="_blank">^</a>] - CodePlex</li> </ul> Keep your multi-core CPU busy with F#, 24 Mar 2007 23:13:48 GMTCode which makes it possible to write applications that take advantage of multi-core CPUs by parallelizing F# filter and map functions.Tomas Petricek<p>The growth of computer CPU speed is slowly being replaced by the growth of number of CPUs (or cores) in the computer at least for the close future. This causes a revolution in the way software is written, because traditional and most widely used way of writing concurrent applications using threads is difficult and brings several serious issues. Some predictions say that within a few years, almost every computer will have about 16 cores, so there is a huge need for programming paradigms or idioms that help developers write concurrent software easily (see also <a href="">The Free Lunch Is Over</a> [<a href="" target="_blank">^</a>] written by Herb Sutter).</p> <p>Functional programming languages (especially pure functional languages) are interesting from this point of view, because the program doesn't have side-effects which makes it very easy to parallelize it (programs in pure functional languages can't have any side-effects by design, in other functional languages like F# the side-effects can be eliminated by following functional programming style). </p> <p>This article describes the code that makes it possible to parallelize some common F# constructs like the <code></code> and <code>List.filter</code>...</p>CLinq - LINQ support for the C++/CLI language, 02 Mar 2007 17:11:05 GMTCLinq project is a library that makes it possible to use LINQ technologies from the C++/CLI language.Tomas Petricek<p>I started working on this project, because I attended C++ class at our university and I had to do some application in C++. Because I hate doing useless projects I wanted to work on something interesting and so I started thinking whether it would be possible to enable LINQ support in C++/CLI...</p> <p>C++/CLI is a very flexible language and the following example proves that enabling LINQ support in C++/CLI isn't impossible. The following database query returns name of contact and company for all customers living in London:</p> <pre lang="c++"> // create connection to database NorthwindData db(".. connection string .."); // declare database query Expr&lt;Customers^&gt; cvar = Var&lt;Customers^&gt;("c"); CQuery&lt;String^&gt;^ q = db.QCustomers -&gt;Where(clq::fun(cvar, cvar.City == "London")) -&gt;Select(clq::fun(cvar, cvar.ContactName + Expr&lt;String^&gt;(", ") + cvar.CompanyName)); // execute query and output results for each(String^ s in q-&gt;Query) Console::WriteLine(s); </pre> <p>If you are interested in more information about CLinq project you can...</p> <ul> <li><a href="/articles/clinq-project.aspx">.. continue and read the entire article</a></li> <li><a href="">Visit the CodePlex project homepage</a> [<a href="" target="_blank">^</a>]</li> </ul>Overload resolution in Phalanger, 15 Feb 2007 21:46:45 GMTPHP doesn't support method overloading, so Phalanger has to solve an interesting problem when calling overloaded .NET method from PHP.Tomas Petricek<p>PHP language itself doesn't method support overloading (having two methods with same name, but different number or types of parameters). This brings an interesting problem to Phalanger, because most of .NET languages support this and if we want to be able to call any .NET object from PHP we need to add support (at least) for calling of overloaded methods. The latest Phalanger release contains overload resolution described in the <em>Integrating PHP with CLR</em> document [<a href="#phpoverloadlnk">1</a>].</p> <p>For example, when calling the <code>Console::WriteLine</code> method (which has a lot of overloads), Phalanger dynamically generates a piece of code that we call dynamic stub, which is responsible for choosing the most appropriate overload depending on the actual parameter types. This stub is generated only once for every method, which makes this implementation very efficient. The difficult part of overload resolution is, how can the stub determine what is the best overload? PHP language has a lot of implicit conversions, so when you pass the string <code>"10.2 Little Piggies"</code> to a method it can be implicitly converted to float (<code>10.2</code>) (For more details see [<a href="#phpoverloadlnk">2</a>]). Another example of implicit conversion is that any boolean value can be converted to string (empty string or string <code>"0"</code> are converted to <code>false</code>, every other string is converted to <code>true</code>).</p> <p>In this article I'll describe how does the dynamic stub look like in current version of Phalanger, what problems can it cause and how are we going to fix it in the future version!</p>Quotations Visualizer for F#, 14 Feb 2007 23:35:03 GMTLittle update to my F# quotations visualizer tool to make it compatible with the latest version of F# ( Petricek<p>Quotation Visualizer is my tool that shows visual representation of F# quotations. Stephen noticed (Thanks!) that Quotation Visualizer doesn't compile with the latest version of F# (, so here is the updated version:</p> <ul> <li><a href="">Download executable</a> (51kB)</li> <li><a href="">Download sources</a> (77kB)</li> </ul> <p class="noindent">If you want to know more about this tool, here are links to previous articles about it:</p> <ul> <li><a href="">F# quotations visualizer</a></li> <li><a href="">F# quotations visualizer - reloaded!</a></li> </ul> <h2>What was wrong?</h2> <p>This tool is written using F# light syntax, which means that you don't have to write all the semicolons and F# compiler uses whitespace to determine end of the blocks (and some other constructs). This compiler option is relatively new so it is still evolving. First issue that I had is with class declaration - the following code is not valid with the latest F# version:</p> <pre lang="fsharp"> type MyForm = class inherit Form as base // ... end </pre> <p>I used it because it looks more familiar to C# developers :-). Instead of it you have to write the following:</p> <pre lang="fsharp"> type MyForm = class inherit Form as base // ... end </pre> <p>The second issue was with the pipeline operator which is useful when working with lists (or other sequences). The correct syntax for using pipeline operator (for expressions that are longer than one line) is following:</p> <pre lang="fsharp"> let filteredList = oldArray |&gt; Array.to_list |&gt; ( fun m -&gt; /* ... */ ) |&gt; List.filter ( fun m -&gt; /* ... */ ) </pre> Compiling Texy! with Phalanger, 12 Feb 2007 00:45:45 GMTThis article describes how to compile Texy! with Phalanger and how to use the produced assembly in ASP.NET application written in C#.Tomas Petricek<p>Texy! [<a href="#texyphallinks">1</a>] is a convertor from text format (similar to formats used in some wiki applications) to valid XHTML code written in PHP. The syntax is described at Texy! web page [<a href="#texyphallinks">2</a>]. Unfortunately, it is only in Czech language, but the syntax is very straightforward, so you can understand it without learning Czech :-).</p><p> In this article, we'll examine how to compile Texy! using Phalanger in pure mode. In this mode it is possible to use objects from PHP like any other .NET objects, so we can later used the compiled assembly for example in the following C# code:</p> <pre> <span class="c">// Create instance of Texy! parser</span> Texy t = <span class="k">new</span> Texy(); <span class="c">// Call the 'process' method and cast result to string</span> <span class="k">string</span> parsed = (<span class="k">string</span>)t.process(txtTexy.Text); <span class="c">// Display parsed text using literal</span> ltrOutput.Text = parsed; </pre>Can't return anonymous type from method? Really?, 23 Jan 2007 23:54:31 GMTThis article describes anonymous types - one of the new C# 3.0 features and shows interesting trick that can be used when returning anonymous type from method.Tomas Petricek<p>One of the new features introduced in C# 3.0 which will be available in Visual Studio "Orcas" (currently in CTP version) is anonymous type. Anonymous type is something very similar to tuple type from Cω [<a href="#returnanonymous">1</a>] (which is based on tuple types known from many functional programming languages including F#). Anonymous types are extremely useful in LINQ queries, because it allows you to construct type with several properties without declaring the type (with all the properties). Example of query with anonymous type looks like this:</p> <pre lang="csharp"> var q = from c in db.Customers where c.Country = "Czech Republic" select new { FullName=c.Name+" "+c.Surname, Address=c.Address }; </pre> <p>Ok, it's probabbly not the best example, but it demonstrates the point - you want to return some information from query and you don't need to declare type that contains <code>FullName</code> and <code>Address</code> properties before, because you need it only for this single query (and you want to return only these two fields, so you don't transfer additional data that you don't need from database).</p><p>Now let's get to the second point... </p> Phalanger has a new website!, 14 Jan 2007 00:49:42 GMTArticle about Phalanger project with links to some interesting articles about Phalanger and describtion of the new web site.Tomas Petricek<p>As you may know, I became new project lead for the <a href="">Phalanger project</a> [<a href="" target="_blank">^</a>]. Phalanger was started as a project at Charles University (where I'm studying) by Tomas Matousek, Ladislav Prosek and 4 other guys, the first version was very successful and they started wokring on the second version which introduces PHP in the family of first-class .NET languages (which makes it fully interoperable with the rest of .NET world). After releasing the second version, Tomas and Ladislav moved to Microsoft and convinced me to continue in the Phalanger development. Most of the work on the 2.0 version was already done, so we're currently working on implementing the rest of the PHP/CLR language extensions, making Phalanger more compatible with existing PHP apps and so on. For more information about the history of Phalanger visit the <a href="">project history page</a> [<a href="" target="_blank">^</a>].</p> <p>I think that Phalanger is in the phase when it can be very interesting for both PHP and .NET communities, but it never got greater publicity and there are not very much examples and articles to demonstrate the interesting Phalanger features. To improve this we started working on the new Phalanger website where users could share their experiences, tips etc. We used PHP wiki called <a href="">DokuWiki</a> [<a href="" target="_blank">^</a>] (running, of course on Phalanger) and you can find the new website here:</p> <ul> <li><a href="">Phalanger - Homepage</a> [<a href="" target="_blank">^</a>] (the new project homepage)</li> <li><a href="">Phalanger - User wiki</a> [<a href="" target="_blank">^</a>] (you can edit pages in user wiki after logging in)</li> </ul> <p>I also wrote two articles about Phalanger (and I'm working on more :-)) to explain the most important and interesting Phalanger features and concepts. You can find the articles at our web:</p> <ul> <li> <a href="">Phalanger for .NET developers</a> [<a href="" target="_blank">^</a>] - focused on .NET interoperability and features interesting for C# developers </li> <li> <a href="">Phalanger for Mono users</a> [<a href="" target="_blank">^</a>] - Phalanger 2.0 supports Mono, so here is an introduction for Mono users</li> </ul> <p>I'll also continue blogging about Phalanger, so you can expect more information about Phalanger, problems that we're currently solving as well as some other tips, tricks in this blog. If you're interested only in Phalanger you can use <a href="">this RSS feed</a> to monitor new articles in this blog (it shows only articles with the Phalanger tag).</p>F# presentation at Czech .NET Group meeting, 14 Nov 2006 00:52:59 GMTContains links to slides and demos from my presentation focused on F# and functional programming, which I did at the Czech .NET User Group meeting.Tomas Petricek<p>On 2nd of November I did a presentation on F# and functional programming at the Czech .NET User Group meeting. Because I spent quite a lot of time with puting the presentation together I wanted to make it available to wider audience, so I translated the slides and examples to English (anyway, translating the content took me only a few minutes :-)). In case that some of the readers prefer Czech version, I attached the original documents too.</p><p>In the presentation I tried to introduce some basic concepts of functional programming (immutable values, lazy evaluation) to the audience with no experience with functional programming, as well as present some of the most interesting features of F# (like strict type system based on type inference, .NET interoperability and metaprogramming). The whole contents of the presentation is following:</p><ul><li><strong>Functional programming in F#</strong> - Introduction to the F# type system</li><li><strong>Some useful functional idioms</strong> - How to do Foldl/Map/Filter functions and Lazy evaluation in C#</li><li><strong>Interactive scripting</strong> - What is important for scripting, mathematical simulation</li><li><strong>Interoperability between F# and other .NET languages</strong> - How to use .NET libraries from F# and F# libraries from ohter .NET languages</li><li><strong>F# as a language for ASP.NET</strong> - How to use F# as a language for ASP.NET development</li><li><strong>Meta-programming in F#</strong> - Meta-programming features in F# and the FLINQ project</li></ul><h2>Downloads</h2><ul><li>Presentation - <a href="">Czech</a> (889 kB), <a href="">English</a> (894 kB)</li><li>Demos - <a href="">Czech</a> (500 kB), <a href="">English</a> (501 kB)</li></ul>Concepts behind the C# 3.0 language, 15 Oct 2006 15:19:03 GMTIn this article I'll describe concepts that influenced the design of the C# 3.0. Most of these concepts are known from other programming languages like Haskell, LISP or languages developed at Microsoft Research.Tomas Petricek<p>One of the lectures that I attended last year was <a href="">Programming Methodology and Philosophy of Programming Languages</a>. The lecture was mostly about history of programming languages and how several features evolved, disappeared and than after many years appeared again in another programming language.</p><p>As I final work I decided to write an article that describes ideas that influenced the design of the C# 3.0 language. Some of these features are known from functional languages (for example from LISP or Haskell), some other were developed at Microsoft Research and appeared in the F# language or Cω. I also wanted to show in what ways are these features limited in the C# 3.0. I think that thanks to these limitation, the C# 3.0 is still a simple (or at least not difficult) to understand which is very important for mainstream language, but I find it interesting to know what is possible in other (less limited) languages.</p><ul><li>You can also <a href="">download the article in PDF</a> (404kB)</li><li>The article is also available at <a href=""></a></li></ul>F# metaprogramming and classes, 14 Oct 2006 01:36:10 GMTThis article presents prototype that makes it possible to use F# metaprogramming to analyse and translate classes written in special way. Tomas Petricek<p>F# quotations allows you to easily write programs that manipulate with data representation of program source code. If you're not familiar with quotations I recommend reading my previous article [<a href="#fsclassmeta-links">1</a>] that contains short introduction to this topic first. Quotations can be used for example for translating subset of the F# language to another code representation or another language.</p><p>To get the quotation data of the expression you can either use <code>&lt;@ .. @&gt;</code> operator or <code>resolveTopDef</code> function. In the first case the code written between the "<code>&lt;@</code>" and "<code>@&gt;</code>" is converted to data during the compilation. The <code>resolveTopDef</code> function allows you to get quotation data of top-level definition (function) from compiled library at runtime (you have to use <code>--quotation-data</code> command line switch while compiling the library). I mentioned that quotations can be used to represent only subset of the F# language. Currently, one of the quotation limitations is that it's not possible to enclose the whole class in the quotation operators. It is also not possible to get the representation of the whole class at runtime nor the representation of class members (for example methods). </p><p>In this article I'll present a simple method that makes it possible to use F# quotations for working with classes as well, however this is rather a prototype that can be used for experimenting and discovering areas where working with classes might be useful, not a fully working solution.</p>F# quotations visualizer - reloaded!, 01 Oct 2006 21:39:06 GMTNew and improved version of quotation visualizer. Supports more language constructs and makes it possible to open quotations from compiled F# assembly.Tomas Petricek<div style="float:right;margin-left:10px;"><a href="" target="_blank"><img style="margin:10px;border-style:none;" src="" alt="Quotation Visualizer" /></a></div><p>Some time ago, I wrote an article about useful utility called <a href="">F# quotations visualizer</a>. This utility can be used to show visual representation of F# quotations, that can represent (subset of) source code written in F#. There are two ways that you can use to get F# quotations - first is using operators <code>&lt;@@ ... @@&gt;</code> (this returns quotation of the code written inside the operator), second method is to get quotation of top level definition from compiled F# assembly (you have to explicitly enable this using command line switch <code>--enable-quotation-data</code> while compiling assembly). </p><p>Because I added several new features to the original Quotations visualizer, I decided to publish the latest version - here is the list of main improvements:</p><ul><li>Rewritten using active patterns (new F# language feature)</li><li>It is possible to extract quotations from compiled F# assembly (if it contains quotation data)</li><li>Added support for several missing language constructs</li></ul>F# CodeDOM Provider on the CodePlex, 23 Aug 2006 00:13:46 GMTCodeDOM generator for the F# language posted to the new Microsoft community site called CodePlex!Tomas Petricek<p>You probably already saw my post regarding CodeDOM generator for the F# language and how to use it with ASP.NET. To make it more accessible for everyone, I created project at the new Microsoft community site called <a href="">CodePlex</a> [<a href="" target="_blank">^</a>].</p><ul><li>To learn more about the project, visit <a href="">Project Home Page</a></li><li>If you want to send some comments, go to <a href="">Discussion Board</a></li><li>You can also download latest source code - <a href="">Latest Check-Ins</a></li><li>And finally, the latest releases can be found at the <a href="">Releases Page</a></li></ul><p> BTW: CodePlex looks like a really good site. It is based on Visual Studio Team System (which means that developers of the project can do most of the work directly from Visual Studio). It provides management of "Work Items" (TODO list), source control and many other useful things! For example if you have any feature requests or bug requests, send them to the discussion and I can easilly create work item from the message in the discussions. </p><p> If you are interested in this project and you want to help with developing of some parts, or if you are working on a project that is related to CodeDOM and F#, please let me know. Any help or feedback is kindly welcome! </p>ASP.NET web applications in F#, 13 Aug 2006 21:06:33 GMTThis article shows how ASP.NET can be extended to support F# language using CodeDOM provider.Tomas Petricek<p>CodeDOM (Code Document Object Model) is set of objects (located in <code>System.CodeDom</code> namespace) that can be used for representing logical structure of .NET source code. These classes are used for generating Web service references (using <code>wsdl.exe</code> tool), for generating typed datasets and in many other situations. The most interesting use of CodeDOM classes is in ASP.NET where ASP.NET generates code from <code>aspx</code>/<code>ascx</code> files and compiles this code into web site assemblies (together with the code written in code behind files).</p><p>This means, that you can use any language for developing ASP.NET web sites, as long as you implement CodeDOM provider that generates source code from CodeDOM structure and can compile these source files (this can be simply done by executing command line compiler). I was recently working on CodeProvider for the F# language, and finally it supports everything what is needed by ASP.NET (however it is complete and it doesn't work for example with <code>wsdl.exe</code>). Using this CodeDOM provider you can write ENTIRE web site in F# (including in-line code enclosed in &lt;% ... source code ... %&gt;). I also created project template for F# web site that can be imported to Visual Studio 2005, so you can easilly try writing web pages in F#...</p>LINQ extensions - Simplified keyword search, 28 Jul 2006 03:57:38 GMTArticle describes LINQ extension that adds support for returning rows that contain any or all of specified keywords in string column.Tomas Petricek<p>Recently, I came across interesting question at LINQ Forums (Dynamic conditions: How to achieve multiple "OR" conditions with LINQ? [<a href="#updlq">1</a>]). The question is whether LINQ (and especially LINQ to SQL) provides any simple way to return only records that contain one or more of specified keywords in the name. The question looks simple, but it is simple only if you know the number of keywords that you want to look for. In this case you can write following LINQ query:</p><pre><span class="c">// Products that contain "kwd1" or "kwd2" in the name </span><br /><span class="k">var</span> q = <span class="k">from</span> p <span class="k">in</span> db.Products <span class="k">where</span> p.ProductName.Contains("kwd1") || p.ProductName.Contains("kwd2") <span class="k">select</span> p; </pre><p>The problem with previous code is that you can't use it if the list of keywords is dynamically entered by user (and so its length may vary). Of course, if you want to run query on in-memory data, you can get very nice results by writing extension method called <code>ContainsAny</code> that performs test for keyword array, but if you want to be able to translate query to SQL, the situation is a bit complicated.</p>F# quotations visualizer, 21 Jun 2006 02:20:03 GMTApplication that displays graphical representation of given F# quotation (using Windows Forms TreeView control)Tomas Petricek<p>I already <a href="">explained</a> what F# quotations are and I explained how you can do some simple manipulations with it. In this article I'd like to present an application that I wrote and that can be helpful when working with quotations. It displays clear graphical representation of given F# quotation (using Windows Forms TreeView control). </p><div style="text-align:center;"><a href="" target="_blank"><img style="margin:10px;border-style:none;" src="" alt="Quotation Visualizer" /></a></div>Calling functions in LINQ queries, 10 Jun 2006 14:26:52 GMTThis article describes method that allows you to reuse parts of LINQ queries across data access layer.Tomas Petricek<p>The <a href="">LINQ Project</a> [<a href="" target="_blank">^</a>] is an extension to .NET Framework and most important .NET languages (C# and VB.Net) that extends these languages with query operators and some language features that make it possible to integrate queries in the languages. Thanks to LINQ you can write queries that read data from database (or any other data source). For example, imagine that you want to write set of queries for eshop and you need to perform a price calculation in more queries. The problem with LINQ queries is that you can't simply call a function written in C# that calculates price. The following example is NOT WORKING for this reason:</p><pre><span class="c">// function used in filter</span><br /><span class="k">static</span> <span class="k">decimal</span> CalcPrice(Nwind.Product p) { <span class="k">return</span> p.UnitPrice * 1.19m; }</pre><pre><span class="c">// query that uses MyFunc</span><br /><span class="k">var</span> q = <span class="k">from</span> p <span class="k">in</span> db.Products <span class="k">where</span> CalcPrice(p) &gt; 30m <span class="k">select</span> p </pre><p>I think that this is a big limitation, because when you want to keep some more complex logic in the data access layer you should be able to reuse parts of queries that are similar across more queries. The good thing is that with latest release, LINQ became extensible so it is possible to write a extensions that allow this scenario...</p><ul><li>You can also <a href="">download the article in PDF</a> (80kB)</li></ul>Slides and demos from F# presentation, 09 Jun 2006 21:14:39 GMTI did a F# presentation at .NET seminar at our university, so here are the slides and demos...Tomas Petricek<p>This semester I attended Advanced .NET Seminar that was led by <a href="">Tomas Matousek</a> [<a href="" target="_blank">^</a>] who is one of the authors of <a href="">Phalanger project</a> [<a href="" target="_blank">^</a>] (Which is an amazing project by the way. It takes PHP source code and compiles it without any modification to .NET). Seminar was mostly focused on Rotor and .NET internals, so if you want to learn more about these topics you can look at <a href="">Advanced .NET programming</a> [<a href="" target="_blank">^</a>] slides (by Tomas Matousek).</p><p>I did one presentation at this seminar too. It was about the F# language developed at Microsoft Research. It was just a quick overview of F# features, because F# is very rich topic, so it coveres only the language (functional vs. imperative behavior), F# type system, compilation of F# constructs to .NET and interoperability with .NET (for example how to create windows forms application in F#). At the end, I also mentioned F# meta-programming that allows you to look at F# code as data.</p><ul><li><a href="">The F# language</a> (67kB) - presentation slides in PDF</li><li><a href="">F# Samples</a> (54kB) - zipped VS 2005 solution with samples</li></ul>F# - Simple quotations transformation, 28 May 2006 15:58:20 GMT This article describes very simple code that I wrote while learning how to work with the F# quotations library. Tomas Petricek<p>This article describes very simple code that I wrote while learning how to work with the F# quotations library. Using the F# quotations you can get tree representation of the quoted expression. This allows you to write code that takes code written in F# as data and performs some code analysis or compiles/translates that code to different language. This is very similar to the new C# 3.0 expression trees where you can get expression tree from lambda expression and translate this tree for example to SQL (using DLINQ). However expression trees in C# 3.0 are very limited when compared with F# quotations, so that's one of the many reasons why F# is interesting language.</p>Aho-Corasick string matching in C#, 04 Dec 2005 00:18:30 GMTC# implementation of very efficient Aho-Corasick keyword matching algorithm with multiple keywords support.Tomas Petricek<p>I implemented this algorithm because I worked on one project where we needed to filter bad language in comments submited by users (You wouldn't believe what anonymous users sometimes write). First I tried simple solution using <code>String.IndexOf</code> and using <code>Regex</code>, but none of these solutions was very suitable for this problem, so I decided to implement Aho-Corasick algorithm which is probabbly the best algorithm for this purpose.</p><p>Article (published here an on describes implementation of this algorithm for pattern matching. In simple words this algorithm can be used for searching text for specified keywords. This implementation is usefull when you have a set of keywords and you want to find all occurences in text or check if any of the keywords is present in the text. You should use this algorithm especially if you have large number of keywords that don't change often, because in this case it is much more efficient than other algorithms that can be simply implemented using .NET class library.</p><p>Aho-Corasick search algorithm is very efficient if you want to find large number of keywords in the text, but if you want to search only for a few keywords it is better to use simple method using <code>String.IndexOf</code>. </p>