<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/rss2full.xsl" type="text/xsl" media="screen"?><?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/itemcontent.css" type="text/css" media="screen"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>Chris Smith's completely unique view</title><link>http://blogs.msdn.com/chrsmith/default.aspx</link><description>F#, more F#, and maybe other stuff.</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/ChrisSmithsCompletelyUniqueView" type="application/rss+xml" /><item><title>ICFP Programming Contest</title><link>http://feeds.feedburner.com/~r/ChrisSmithsCompletelyUniqueView/~3/335595305/icfp-programming-contest.aspx</link><pubDate>Mon, 14 Jul 2008 23:49:02 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8732359</guid><dc:creator>ChrSmith</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/chrsmith/comments/8732359.aspx</comments><wfw:commentRss>http://blogs.msdn.com/chrsmith/commentrss.aspx?PostID=8732359</wfw:commentRss><description>&lt;p&gt;As far as elite programming contests go, I thought the only one around was the &lt;a href="http://cm2prod.baylor.edu/login.jsf"&gt;ACM-ICP&lt;/a&gt;. (The ACM International Collegiate Programming Contest.) However there is a less well known but arguably more hard core contest called the &lt;a href="http://www.icfpconference.org/"&gt;ICFP&lt;/a&gt;. &lt;/p&gt;  &lt;p&gt;Each year as part of &lt;em&gt;The International Conference on Functional Programming&lt;/em&gt; there is a programming contest in which the first prize is an official declaration that:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;“The first place team's language is the programming language of choice for discriminating hackers”&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Of course we all know the language of choice for discriminating hackers is F#, but if that could be proven by winning this completion then great! So &lt;a href="http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!277.entry"&gt;Brian McNamara&lt;/a&gt;, &lt;a href="http://blogs.msdn.com/lukeh/"&gt;Luke Hoban&lt;/a&gt;, &lt;a href="http://diditwith.net/default.aspx"&gt;Dustin Campbell&lt;/a&gt;, and &lt;a href="http://blogs.msdn.com/chrsmith"&gt;Myself&lt;/a&gt; formed team &lt;font face="Courier New"&gt;Cup&amp;lt;’t&amp;gt;&lt;/font&gt;.&lt;/p&gt;  &lt;p&gt;You can get the full ICFP 2008 problem description &lt;a href="http://smlnj.org/icfp08-contest/task.html"&gt;here&lt;/a&gt;, but generally it was write an AI for a Mars rover which avoids obstacles and blood thirsty Martians. I’ve never written a ‘real time’ app before and found the whole robotics domain pretty enjoyable. (Maybe you’ll start seeing blog posts using &lt;a href="http://msdn.microsoft.com/en-us/robotics/default.aspx"&gt;Robotics Developer Studio&lt;/a&gt;.)&lt;/p&gt;  &lt;p&gt;Anyways, if you missed out on the competition I definitely encourage you to participate next year. We had a total blast.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/chrsmith/WindowsLiveWriter/ICFPProgrammingContest_EA64/iPhone%20004.jpg"&gt;&lt;img title="Team Cup&amp;lt;&amp;#39;t&amp;gt;" style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="456" alt="Team Cup&amp;lt;&amp;#39;t&amp;gt;" src="http://blogs.msdn.com/blogfiles/chrsmith/WindowsLiveWriter/ICFPProgrammingContest_EA64/iPhone%20004_thumb.jpg" width="551" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;Pictured from left: Brian McNamara, Luke Hoban, Anson Horton, Alex Turner&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8732359" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/ChrisSmithsCompletelyUniqueView/~4/335595305" height="1" width="1"/&gt;</description><category domain="http://blogs.msdn.com/chrsmith/archive/tags/ICFP/default.aspx">ICFP</category><feedburner:origLink>http://blogs.msdn.com/chrsmith/archive/2008/07/14/icfp-programming-contest.aspx</feedburner:origLink></item><item><title>Mastering F# Lists</title><link>http://feeds.feedburner.com/~r/ChrisSmithsCompletelyUniqueView/~3/332414179/mastering-f-lists.aspx</link><pubDate>Fri, 11 Jul 2008 03:49:46 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8719929</guid><dc:creator>ChrSmith</dc:creator><slash:comments>4</slash:comments><comments>http://blogs.msdn.com/chrsmith/comments/8719929.aspx</comments><wfw:commentRss>http://blogs.msdn.com/chrsmith/commentrss.aspx?PostID=8719929</wfw:commentRss><description>&lt;p&gt;Lists represent the backbone of functional programming and in order to be an effective F# programmer you must truly master list processing. Fortunately lists are simple and straight forward, so let’s begin. &lt;h1&gt;Mastering F# Lists&lt;/h1&gt; &lt;p&gt;There are several things which distinguish the F# list type from the .NET Arrays and generic List&amp;lt;T&amp;gt; type in the System.Collections.Generic namespace.  &lt;p&gt;&lt;b&gt;&lt;/b&gt;&lt;/p&gt; &lt;table cellspacing="0" cellpadding="2" width="419" border="1"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td valign="top" width="151"&gt;&amp;nbsp;&lt;/td&gt; &lt;td valign="top" width="81"&gt;F# List&lt;/td&gt; &lt;td valign="top" width="77"&gt;Arrays&lt;/td&gt; &lt;td valign="top" width="108"&gt;Generic List&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="151"&gt;Modify Elements&lt;/td&gt; &lt;td valign="top" width="81"&gt;No&lt;/td&gt; &lt;td valign="top" width="77"&gt;Yes&lt;/td&gt; &lt;td valign="top" width="108"&gt;Yes&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="151"&gt;Add New Elements&lt;/td&gt; &lt;td valign="top" width="81"&gt;No&lt;/td&gt; &lt;td valign="top" width="77"&gt;No&lt;/td&gt; &lt;td valign="top" width="108"&gt;Yes&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="151"&gt;Element Lookup&lt;/td&gt; &lt;td valign="top" width="81"&gt;O(n) slow&lt;/td&gt; &lt;td valign="top" width="77"&gt;O(1) fast&lt;/td&gt; &lt;td valign="top" width="108"&gt;O(1) fast&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt; &lt;p&gt;After looking at that chart, you might be wondering why even use F# lists at all? Element lookup is slow and you can’t even modify the thing once it has been created, so why bother. The reason why is that &lt;strong&gt;F# lists are immutable&lt;/strong&gt;. Unlike arrays and generic lists, F# lists are guaranteed never to change once they have been created. If you have a type that returns an array or List&amp;lt;T&amp;gt; you don’t know what the outside world will do to it, check out Jomo’s &lt;a href="http://blogs.msdn.com/jomo_fisher/archive/2007/05/16/leaky-functions-barrel-of-bugs.aspx"&gt;Barrel of Bugs&lt;/a&gt; blog post for details. &lt;p&gt;But seriously, is this safety worth it? Yes. If used correctly in the right situations, F# lists can be more efficient than .NET Arrays or generic Lists. So let’s dig into looking at how F# lists work. &lt;h2&gt;Linked Lists&lt;/h2&gt; &lt;p&gt;F# lists are represented as &lt;a href="http://en.wikipedia.org/wiki/Linked_lists"&gt;linked lists&lt;/a&gt;, which are a foundational Computer Science data structure abstracted by links in a chain. Each individual link has a piece of data associated with it and may be connected to another link. The last link isn’t connected to anything, so it ‘points to null’ or the empty list []. (&lt;em&gt;Ed. Sorry the empty list looks like a square block in my images.)&lt;/em&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/chrsmith/WindowsLiveWriter/MasteringFLists_CA2A/clip_image001%5B1%5D.png"&gt;&lt;img title="clip_image001[1]" height="44" alt="clip_image001[1]" src="http://blogs.msdn.com/blogfiles/chrsmith/WindowsLiveWriter/MasteringFLists_CA2A/clip_image001%5B1%5D_thumb.png" width="240"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;There are two main operations on a list: Cons (adding a single element) and Concat (joining two lists). &lt;h3&gt;Cons&lt;/h3&gt; &lt;p&gt;Cons is where you add an element to the beginning of a list. In F# the type of the cons function’s type is:&lt;pre class="code"&gt;‘a –&amp;gt; ‘a list –&amp;gt; ‘a list&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;The important thing to understand is that cons executes in constant, O(1), time. To join an element to an immutable linked list all you need to do is put that value in a list node and set its ‘next list node’ to be the first element in the existing list. Everything ‘after’ the new node is none the wiser. 
&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/chrsmith/WindowsLiveWriter/MasteringFLists_CA2A/clip_image002%5B1%5D.png"&gt;&lt;img title="clip_image002[1]" height="54" alt="clip_image002[1]" src="http://blogs.msdn.com/blogfiles/chrsmith/WindowsLiveWriter/MasteringFLists_CA2A/clip_image002%5B1%5D_thumb.png" width="301"&gt;&lt;/a&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;gt; 1 :: [2 .. 4];;&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;val it : int list = [1; 2; 3; 4]&lt;/font&gt;
&lt;h3&gt;Concat&lt;/h3&gt;
&lt;p&gt;Concat joins two lists together. The function type for concat is:&lt;pre class="code"&gt;‘a list –&amp;gt; ‘a list' –&amp;gt; ‘a list&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;In order to join two lists all you need to do is set the ‘next node’ value in the &lt;em&gt;last element&lt;/em&gt; of the first list equal to the first node in the second list. This sounds like a great solution, but remember &lt;b&gt;you cannot modify list elements&lt;/b&gt;. So to join to lists you actually need to make a copy of the first list just so you can change what the last element points to. For this reason, execution of concat is on order O(n) where n is the number of elements in the first list. Visually you can see this by:
&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/chrsmith/WindowsLiveWriter/MasteringFLists_CA2A/clip_image003%5B1%5D.png"&gt;&lt;img title="clip_image003[1]" height="156" alt="clip_image003[1]" src="http://blogs.msdn.com/blogfiles/chrsmith/WindowsLiveWriter/MasteringFLists_CA2A/clip_image003%5B1%5D_thumb.png" width="387"&gt;&lt;/a&gt;
&lt;p&gt;To summarize: Cons is fast and easy and Concat is slowish.
&lt;h2&gt;List Module Functions&lt;/h2&gt;
&lt;p&gt;Now that we understand lists, let’s look at some built-in functions for manipulating them. 
&lt;h3&gt;List.hd&lt;/h3&gt;
&lt;p&gt;List.hd returns the first element or head of a list.
&lt;h3&gt;List.tl&lt;/h3&gt;
&lt;p&gt;List.tl returns the ‘tail’ of the first element, of the list of items after the first element.
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;gt; let l = [1; 2; 3];;&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;val l : int list&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;gt; List.hd l;;&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;val it : int = 1&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;gt; List.tl l;;&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;val it : int list = [2; 3]&lt;/font&gt;
&lt;h5&gt;List.length&lt;/h5&gt;
&lt;p&gt;List.length returns the length of the list, nothing special to see here.
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;gt; List.length [1; 2; 3; 4; 5];;&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;val it : int = 5&lt;/font&gt;
&lt;h5&gt;List.rev&lt;/h5&gt;
&lt;p&gt;List.rev reverses a list. This makes a copy of the entire list so be careful when calling it, as it if you use List.rev in an inner loop your performance is hosed.
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;gt; List.rev [1 .. 10];;&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;val it : int list = [10; 9; 8; 7; 6; 5; 4; 3; 2; 1]&lt;/font&gt;
&lt;h5&gt;List.find&lt;/h5&gt;
&lt;p&gt;List.find takes a boolean function and returns the first element where that function returns true. However, if List.find doesn’t ‘find’ the element you are searching for it throws an exception. Since generally throwing exceptions is bad for everyone involved, I recommend List.tryfind instead, which returns an Option value. In this example we look through a list of numbers for one which is equal to the square root of 144.
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;gt; List.find (fun i -&amp;gt; i * i = 144) [1 .. 10];;&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;System.Collections.Generic.KeyNotFoundException: The item was not found in the collection&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;at Microsoft.FSharp.Core.Operators.not_found[T]()&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;at &amp;lt;StartupCode$FSI_0014&amp;gt;.$FSI_0014._main()&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;stopped due to error&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;gt; List.tryfind (fun i -&amp;gt; i * i = 144) [1 .. 10];;&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;val it : int option = None&lt;/font&gt;
&lt;h5&gt;List.filter&lt;/h5&gt;
&lt;p&gt;List.filter takes a function and produces a new list with only the items on which the function returned true. This filters down the list to just what you want. In the example we filter down a list of numbers to only those which are even.
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;gt; List.filter (fun i -&amp;gt; i % 2 = 0) [1 .. 20];;&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;val it : int list = [2; 4; 6; 8; 10; 12; 14; 16; 18; 20]&lt;/font&gt;
&lt;h2&gt;Aggregate Operators&lt;/h2&gt;
&lt;p&gt;The List module also supports a trio of &lt;i&gt;aggregate operators&lt;/i&gt;: iter, map, and fold. These three functions provide all the power you need to do heavy lifting with any collection type. (In fact you will find a subset of iter, map, and fold in the Set, Seq, Option, and Array modules.)
&lt;h3&gt;List.Iter&lt;/h3&gt;
&lt;p&gt;The iter function is perhaps the simplest aggregate operator. All it does is iterates through each element in a list taking calling a function for each element. Note that the iter function doesn’t produce a value. Iterating through a list is predominately used for evaluating the side effects of the provided function, such as printing to the console.
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;gt; List.iter (fun i -&amp;gt; printfn "List contains %d" i) [1 .. 5];;&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;List contains 1&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;List contains 2&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;List contains 3&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;List contains 4&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;List contains 5&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;val it : unit = ()&lt;/font&gt;
&lt;h3&gt;List.Map&lt;/h3&gt;
&lt;p&gt;List.map is used to transform a list of items using a given function. The type of List.map is
&lt;p&gt;&lt;font face="Courier New"&gt;(‘a –&amp;gt; ‘b) –&amp;gt; ‘a list –&amp;gt; ‘b list &lt;/font&gt;
&lt;p&gt;Visually we can see the effects of a map using function &lt;em&gt;f &lt;/em&gt;by:
&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/chrsmith/WindowsLiveWriter/MasteringFLists_CA2A/clip_image004%5B1%5D.png"&gt;&lt;img title="clip_image004[1]" height="268" alt="clip_image004[1]" src="http://blogs.msdn.com/blogfiles/chrsmith/WindowsLiveWriter/MasteringFLists_CA2A/clip_image004%5B1%5D_thumb.png" width="350"&gt;&lt;/a&gt;
&lt;h5&gt;Inverting a list of numbers&lt;/h5&gt;
&lt;p&gt;Imagine we wanted to invert a list of numbers. All we need to do is map the invert function to each element in our list.&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Invert a list of numbers
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;invertNumber x = x * -1

&lt;span style="color: green"&gt;// Inverts numbers 1 through 10
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;x = List.map invertNumber [1 .. 10]

&lt;span style="color: green"&gt;// Prints: [-1; -2; -3; -4; -5; -6; ...]
&lt;/span&gt;printfn &lt;span style="color: maroon"&gt;"%A" &lt;/span&gt;x&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;h3&gt;List.Fold&lt;/h3&gt;
&lt;p&gt;Folds are the most powerful aggregate operator and not surprisingly the most complicated. When you have a list of values and you want to distill it down to a single piece of data you use List.fold. List folds come in two flavors: fold_left and fold_right. The one you use determines the order in which elements are visited. (fold_left going left-to-right and fold_right going right-to-left.)
&lt;p&gt;List.fold iterates through each element of the list and builds up an accumulator value. Once every element has been processed, List.fold returns the final value of the accumulator. The type of List.fold_left is:
&lt;p&gt;&lt;font face="Courier New"&gt;(('a -&amp;gt; 'b -&amp;gt; 'a) -&amp;gt; 'a -&amp;gt; 'b list -&amp;gt; 'a)&lt;/font&gt;
&lt;p&gt;To name the parameters fold_left takes:
&lt;p&gt;&lt;font face="Courier New"&gt;List.fold_left :&amp;nbsp; ([function] accumulator listElement -&amp;gt; accumulator) initialAccumulatorValue theListToFold&lt;/font&gt;
&lt;h5&gt;List.Fold_left&lt;/h5&gt;
&lt;h5&gt;Sum a list of numbers&lt;/h5&gt;
&lt;p&gt;The simplest example of a fold is summing a list of numbers. Our accumulator function will simply add the list element, x, to our accumulator value. &lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Sum a list
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;accumulate acc x = acc + x

&lt;span style="color: blue"&gt;let &lt;/span&gt;sumList = List.fold_left accumulate 0 [1 .. 10]

&lt;span style="color: green"&gt;// Notice our accumulator function is identical to the (+) operator,
// so we can rewrite our fold as:
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;conciseSum = List.fold_left (+) 0 [1 .. 10]&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;The accumulator value doesn’t need to be a primitive value though, perhaps you want to reduce a list to different pieces of data. You can have that accumulator be a tuple to store multiple values or even a record to store structured data.
&lt;h5&gt;Counting vowels&lt;/h5&gt;
&lt;p&gt;Before I go into the next example, let me quickly review an elegant syntax for cloning records:&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Cloning Records
&lt;/span&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;Car = { Make : string; Model : string; Year : int }

&lt;span style="color: blue"&gt;let &lt;/span&gt;eclipse   = { Make = &lt;span style="color: maroon"&gt;"Mitsubishi"&lt;/span&gt;; Model = &lt;span style="color: maroon"&gt;"Eclipse"&lt;/span&gt;; Year = 2005 }

&lt;span style="color: green"&gt;// You could make a copy like this ...
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;nextYears1 = { Make = eclipse.Make; Model = eclipse.Model; Year = 2006 }
&lt;span style="color: green"&gt;// .. but an easier way would be this.
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;nextYears2 = { eclipse &lt;span style="color: blue"&gt;with &lt;/span&gt;Year = 2006 }&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Here’s another example of List.fold_left, totaling the number of vowels in a sentence. For our accumulator we will use a record.&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Counting vowels
&lt;/span&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;VowelCount = { A : int; E : int; I : int; O : int; U : int }

&lt;span style="color: blue"&gt;let &lt;/span&gt;countVowels acc c =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;c &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| 'a' &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;{ acc &lt;span style="color: blue"&gt;with &lt;/span&gt;A = acc.A + 1 }
    | 'e' &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;{ acc &lt;span style="color: blue"&gt;with &lt;/span&gt;E = acc.E + 1 }
    | 'i' &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;{ acc &lt;span style="color: blue"&gt;with &lt;/span&gt;I = acc.I + 1 }
    | 'o' &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;{ acc &lt;span style="color: blue"&gt;with &lt;/span&gt;O = acc.O + 1 }
    | 'u' &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;{ acc &lt;span style="color: blue"&gt;with &lt;/span&gt;U = acc.U + 1 }
    | _   &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;acc
    
&lt;span style="color: blue"&gt;let &lt;/span&gt;listOfChars = Seq.to_list &lt;span style="color: maroon"&gt;"The quick brown fox jumps over the lazy dog."

&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;accInitVal = { A = 0; E = 0; I = 0; O = 0; U = 0 }&lt;/pre&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Evaluates to: {A = 1; E = 3; I = 1; O = 4; U = 2;} &lt;/span&gt;&lt;br&gt;&lt;br&gt;List.fold_left countVowels accInitVal listOfChars&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;h5&gt;Fold_right&lt;/h5&gt;
&lt;p&gt;Choosing between List.fold_left and List.fold_right may seem like a cosmetic difference, but &lt;strong&gt;folding order can have a substantial impact on performance&lt;/strong&gt;. Consider the problem of splitting a string. Given a list of characters, return a list of lists of characters representing words separated by spaces.&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// List.fold_left (bad)
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;listOfChars2 = Seq.to_list &lt;span style="color: maroon"&gt;"The quick brown fox jumps over the lazy dog"

&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;breakIntoWords (acc : char list list) c =
    &lt;span style="color: green"&gt;// If the letter isn't a space, add it to our accumulator
    &lt;/span&gt;&lt;span style="color: blue"&gt;if &lt;/span&gt;c &amp;lt;&amp;gt; ' ' &lt;span style="color: blue"&gt;then
        &lt;/span&gt;&lt;span style="color: green"&gt;// Words are stored in order, so the last word is at the end of the list...
        &lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;revAcc = List.rev acc
        &lt;span style="color: green"&gt;// Now get the first item in the reversed list
        &lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;word = List.hd revAcc
        &lt;span style="color: green"&gt;// And add this character at the end
        &lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;updatedWord = word @ [ c ]
        &lt;span style="color: green"&gt;// Finally put this updated word at the end of our accumulator
        &lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;updatedRevAcc = updatedWord :: (List.tl revAcc)
        List.rev updatedRevAcc
    &lt;span style="color: green"&gt;// If the letter is a space then add a new list of chars
    &lt;/span&gt;&lt;span style="color: blue"&gt;else 
        &lt;/span&gt;acc @ [ [] ]
        
&lt;span style="color: blue"&gt;let &lt;/span&gt;words = List.fold_left breakIntoWords [ [] ] listOfChars2

&lt;span style="color: green"&gt;(* Prints:
[['T'; 'h'; 'e']; ['q'; 'u'; 'i'; 'c'; 'k']; ['b'; 'r'; 'o'; 'w'; 'n'];
 ['f'; 'o'; 'x']; ['j'; 'u'; 'm'; 'p'; 's']; ['o'; 'v'; 'e'; 'r'];
 ['t'; 'h'; 'e']; ['l'; 'a'; 'z'; 'y']; ['d'; 'o'; 'g']] *)
&lt;/span&gt;printfn &lt;span style="color: maroon"&gt;"%A" &lt;/span&gt;words&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;The solution doesn’t seem terribly bad, we just need to deal with the inconvenience of reversing the lists and adding elements to the ‘back’. But remember that everything you call List.rev it takes O(n) time. And every type you call (@) that takes another O(n). In short, &lt;strong&gt;that fold was a steaming pile of slow&lt;/strong&gt;. However, because of the nature of that problem if we go ‘backwards’ or fold in right-to-left order we can add characters and words to the front of the list, allowing us to use the much faster Cons function.
&lt;p&gt;Solving this problem using List.fold_right allows us to remove all calls to List.rev and Concat. The resulting fold operation is much more performant.&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// List.fold_right (good)
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;listOfChars3 = Seq.to_list &lt;span style="color: maroon"&gt;"The quick brown fox jumps over the lazy dog"

&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;breakIntoWordsGood c (acc : char list list) =
    &lt;span style="color: green"&gt;// If the letter isn't a space, add it to our accumulator
    &lt;/span&gt;&lt;span style="color: blue"&gt;if &lt;/span&gt;c &amp;lt;&amp;gt; ' ' &lt;span style="color: blue"&gt;then
        &lt;/span&gt;&lt;span style="color: green"&gt;// Words are stored in reverse order, so get the first word
        &lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;word = List.hd acc
        &lt;span style="color: green"&gt;// And add this character at the beginning
        &lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;updatedWord = c :: word
        &lt;span style="color: green"&gt;// Finally put this updated word at the beginning of our accumulator
        &lt;/span&gt;updatedWord :: (List.tl acc)
    &lt;span style="color: green"&gt;// If the letter is a space then add a new list of chars
    &lt;/span&gt;&lt;span style="color: blue"&gt;else 
        &lt;/span&gt;[ [] ] @ acc
        
&lt;span style="color: blue"&gt;let &lt;/span&gt;words2 = List.fold_right breakIntoWordsGood listOfChars3 [ [] ] 

&lt;span style="color: green"&gt;(* Prints:
[['T'; 'h'; 'e']; ['q'; 'u'; 'i'; 'c'; 'k']; ['b'; 'r'; 'o'; 'w'; 'n'];
 ['f'; 'o'; 'x']; ['j'; 'u'; 'm'; 'p'; 's']; ['o'; 'v'; 'e'; 'r'];
 ['t'; 'h'; 'e']; ['l'; 'a'; 'z'; 'y']; ['d'; 'o'; 'g']] *)
&lt;/span&gt;printfn &lt;span style="color: maroon"&gt;"%A" &lt;/span&gt;words2&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;While there is still plenty more to know about lists, now you should be armed with enough knowledge to tackle &lt;a href="http://projecteuler.net/"&gt;Project Euler&lt;/a&gt; problems with ease. 
&lt;p&gt;In closing, I hope you enjoyed this post and if there is any F# topic you would like me to cover in the future blog post please use the Contact link and let me know. Thanks!
&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8719929" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/ChrisSmithsCompletelyUniqueView/~4/332414179" height="1" width="1"/&gt;</description><category domain="http://blogs.msdn.com/chrsmith/archive/tags/F_2300_/default.aspx">F#</category><category domain="http://blogs.msdn.com/chrsmith/archive/tags/Mastering/default.aspx">Mastering</category><feedburner:origLink>http://blogs.msdn.com/chrsmith/archive/2008/07/10/mastering-f-lists.aspx</feedburner:origLink></item><item><title>Some guidelines for readable F# code</title><link>http://feeds.feedburner.com/~r/ChrisSmithsCompletelyUniqueView/~3/320204119/some-guidelines-for-readable-f-code.aspx</link><pubDate>Thu, 26 Jun 2008 02:05:20 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8654360</guid><dc:creator>ChrSmith</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/chrsmith/comments/8654360.aspx</comments><wfw:commentRss>http://blogs.msdn.com/chrsmith/commentrss.aspx?PostID=8654360</wfw:commentRss><description>&lt;p&gt;When learning a new programming language it isn’t enough to know the syntax, you must also take the time to learn the idioms and styles for the language. Unfortunately those idioms and styles develop over years and F# still hasn’t had its ‘official v1'.0’ release. So where do we start?&lt;/p&gt;  &lt;p&gt;We can begin by looking at F#'s roots - C# and OCaml - for guidance:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a title="http://caml.inria.fr/resources/doc/guides/guidelines.html" href="http://caml.inria.fr/resources/doc/guides/guidelines.html"&gt;OCaml programming guidelines&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a title="http://msdn.microsoft.com/en-us/library/xzf533w0(VS.71).aspx" href="http://msdn.microsoft.com/en-us/library/xzf533w0(VS.71).aspx"&gt;.NET naming guidelines&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a title="http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=336" href="http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=336"&gt;C# Coding Style guide&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a title="http://msdn.microsoft.com/en-us/library/ms229042.aspx" href="http://msdn.microsoft.com/en-us/library/ms229042.aspx"&gt;Design Guidelines for Developing Class Libraries&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Once you start looking at those docs however, you'll begin to notice some conflicting advice. The problem isn't just that F# is both functional and object-oriented.&amp;#160; Good design guidelines are hard to pin down because F# can be used to write applications ranging from simple scripts to line-of-buisiness apps to physics simulations.&lt;/p&gt;  &lt;p&gt;So I won't set out to write the ultimate set of coding guidelines for F#, but I will at the very least try to start the dialog. &lt;/p&gt;  &lt;p&gt;For this post I would like to focus on readability. (Caveat Emptor, I completely reserve the right to flip-flop on any of these style issues; you have been warned.)&lt;/p&gt;  &lt;h1&gt;&amp;#160;&lt;/h1&gt;  &lt;h1&gt;F# Don'ts&lt;/h1&gt;  &lt;p&gt;Let's start with the things you shouldn't do. If you want to write obfuscated F# code, here's the way to start.&lt;/p&gt;  &lt;h2&gt;Don't open Namespaces without a fully-qualified path&lt;/h2&gt;  &lt;p&gt;The semantics of &lt;span style="color: blue"&gt;open &lt;/span&gt;are that once you open a namespace, you can then open any nested namespaces without fully-qualifying them. If you do this however, you lose any ability to determine what '&lt;span style="color: blue"&gt;open &lt;/span&gt;X' is actually referring too. Worse yet, you can run into namespace collisions. Recommendation: don't do this.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;open &lt;/span&gt;System
&lt;span style="color: blue"&gt;open &lt;/span&gt;Collections
&lt;span style="color: blue"&gt;open &lt;/span&gt;Generic

&lt;span style="color: green"&gt;// System.Collections.Generic.List&amp;lt;T&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;x = &lt;span style="color: blue"&gt;new &lt;/span&gt;List&amp;lt;string&amp;gt;()&lt;/pre&gt;

&lt;h2&gt;Don't outscope values&lt;/h2&gt;

&lt;p&gt;In F# it is possible to introduce new values outscoping existing ones but since everything is immutable this doesn't modify the value, it simply creates a new one with the same name. To the novice F# developer, the following code would print both &amp;quot;Hello&amp;quot; and &amp;quot;Goodbye&amp;quot; however it does not.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;greet() =
    
    &lt;span style="color: blue"&gt;let &lt;/span&gt;message = &lt;span style="color: maroon"&gt;&amp;quot;Hello&amp;quot;
    
    &lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;printGreeting() = printfn &lt;span style="color: maroon"&gt;&amp;quot;%s Bob&amp;quot; &lt;/span&gt;message
    
    &lt;span style="color: green"&gt;// prints &amp;quot;Hello Bob&amp;quot;
    &lt;/span&gt;printGreeting()
    
    &lt;span style="color: blue"&gt;let &lt;/span&gt;message = &lt;span style="color: maroon"&gt;&amp;quot;Goodbye&amp;quot;
    
    &lt;/span&gt;&lt;span style="color: green"&gt;// prints &amp;quot;Hello Bob&amp;quot;
    &lt;/span&gt;printGreeting()&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;h1&gt;F# Code to Avoid&lt;/h1&gt;

&lt;p&gt;These aren't necessarily bad things, but you need to be careful when using these concepts.&lt;/p&gt;

&lt;h2&gt;Avoid mutable function values&lt;/h2&gt;

&lt;p&gt;Passing around a mutable function value enables some interesting functional programming patterns, but also enables new classes of bugs. You should avoid mutable function values unless they have a very limited scope.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let mutable &lt;/span&gt;mutableFunc = &lt;span style="color: blue"&gt;fun &lt;/span&gt;x y &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;x + y

mutableFunc &amp;lt;- (&lt;span style="color: blue"&gt;fun &lt;/span&gt;x y &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;x * y * -1)
mutableFunc &amp;lt;- (&lt;span style="color: blue"&gt;fun &lt;/span&gt;x y &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;List.length [x .. y])
mutableFunc &amp;lt;- (&lt;span style="color: blue"&gt;fun &lt;/span&gt;x y &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;(box x).ToString().Length + y)

mutableFunc 4 5&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;h2&gt;Avoid abusing type abbreviations&lt;/h2&gt;

&lt;p&gt;Type abbreviations simplify code and increase readability, but if you do it too much you are just introducing new types that need to be remembered by the person maintaining your code.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;string_string_dictionary = Dictionary&amp;lt;string, string&amp;gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;h2&gt;Avoid abusing partial function application (currying)&lt;/h2&gt;

&lt;p&gt;Just like the previous bullet, currying is a great feature when used judiciously. Just be aware that at some point it is possible to go overboard and make your code impossible to debug.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;moveFunc x y = System.IO.File.Move(x, y)

&lt;span style="color: blue"&gt;let &lt;/span&gt;moveFileX = moveFunc &lt;span style="color: maroon"&gt;@&amp;quot;D:\Documents\FileX.fs&amp;quot;

&lt;/span&gt;moveFileX &lt;span style="color: maroon"&gt;&amp;quot;E:\NewFileLocation\FileX.fs&amp;quot;&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;h1&gt;F# Code to Consider&lt;/h1&gt;

&lt;p&gt;These are guidelines which may not always be applicable, but you should consider using them when the situation arises.&lt;/p&gt;

&lt;h2&gt;Prefer Sequence Expressions to Seq.unfold&lt;/h2&gt;

&lt;p&gt;There certainly is a place for Seq.unfold, but Sequence Expressions are much easier to read.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Fibonacci numbers - 1, 1, 2, 3, 5, 8, 13, ...
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;seq_unfold = 
    Seq.unfold 
        (&lt;span style="color: blue"&gt;fun &lt;/span&gt;(idx, last1, last2) &lt;span style="color: blue"&gt;-&amp;gt; 
            if &lt;/span&gt;idx &amp;gt;= 20 &lt;span style="color: blue"&gt;then 
                &lt;/span&gt;None 
            &lt;span style="color: blue"&gt;else 
                &lt;/span&gt;Some(last1 + last2, (idx + 1, last1 + last2, last1))) 
        (0, 0, 1)

&lt;span style="color: green"&gt;// vs.

&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;sequence_expression =
    seq {
        &lt;span style="color: blue"&gt;let &lt;/span&gt;lastStep = ref (0, 1)
        &lt;span style="color: blue"&gt;for &lt;/span&gt;i &lt;span style="color: blue"&gt;in &lt;/span&gt;1 .. 20 &lt;span style="color: blue"&gt;do
            let &lt;/span&gt;x, y = !lastStep
            &lt;span style="color: blue"&gt;yield &lt;/span&gt;x + y
            &lt;span style="color: blue"&gt;do &lt;/span&gt;lastStep := (x + y, x) }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;F# Dos&lt;/h1&gt;

&lt;p&gt;These are things you should always do to aid readability of your F# programs.&lt;/p&gt;

&lt;h2&gt;Use the Pipe-Forward operator wherever possible&lt;/h2&gt;

&lt;p&gt;If you find yourself stringing together a lot of operations, don't write in the lame-imperative way. Use the pipe-forward operator to simplify the code. (Do this only within reason, since you can't store intermediate results long chains of piped functions are actually very hard to debug.)&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;folderSize baseFolder =
    baseFolder
    |&amp;gt; filesUnderFolder
    |&amp;gt; Seq.map getFileInfo
    |&amp;gt; Seq.map getFileSize
    |&amp;gt; Seq.fold (+) 0L 
    |&amp;gt; convertBytesToMB&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;h2&gt;Add comments to Union Type data tags if necessary&lt;/h2&gt;

&lt;p&gt;Currently in F# you cannot name data associated with Union Type data tags, be sure to add a comment around the declaration site so that other programs know what the tag is expected to carry AND the order that data is expected to come in. &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;MotorizedTransport =
    &lt;span style="color: green"&gt;// Model, Year
    &lt;/span&gt;| SUV   &lt;span style="color: blue"&gt;of &lt;/span&gt;string * int
    &lt;span style="color: green"&gt;// Model, Year, Carrying capacity
    &lt;/span&gt;| Truck &lt;span style="color: blue"&gt;of &lt;/span&gt;string * int * int&lt;strong&gt;&amp;#160;&lt;/strong&gt;&lt;/pre&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8654360" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/ChrisSmithsCompletelyUniqueView/~4/320204119" height="1" width="1"/&gt;</description><category domain="http://blogs.msdn.com/chrsmith/archive/tags/Software+Development/default.aspx">Software Development</category><category domain="http://blogs.msdn.com/chrsmith/archive/tags/F_2300_/default.aspx">F#</category><category domain="http://blogs.msdn.com/chrsmith/archive/tags/Style/default.aspx">Style</category><feedburner:origLink>http://blogs.msdn.com/chrsmith/archive/2008/06/25/some-guidelines-for-readable-f-code.aspx</feedburner:origLink></item><item><title>Shameless plug - FsTest</title><link>http://feeds.feedburner.com/~r/ChrisSmithsCompletelyUniqueView/~3/317698511/shameless-plug-fstest.aspx</link><pubDate>Sun, 22 Jun 2008 20:00:27 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8639859</guid><dc:creator>ChrSmith</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/chrsmith/comments/8639859.aspx</comments><wfw:commentRss>http://blogs.msdn.com/chrsmith/commentrss.aspx?PostID=8639859</wfw:commentRss><description>&lt;p&gt;&lt;a href="http://weblogs.asp.net/podwysocki/default.aspx"&gt;Matthew Podwysocki&lt;/a&gt; finished putting together a &lt;a href="http://weblogs.asp.net/podwysocki/archive/2008/06/19/announcing-fstest-a-testing-dsl-for-f.aspx"&gt;DSL for unit testing&lt;/a&gt;. I imagine this only scratches the surface of what you can do with DSLs in F#.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;The same approach also works for scripting too, check out this piece of Zen:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;#light

open &lt;/span&gt;System.IO

&lt;span style="color: green"&gt;// Returns all the files under a given folder
&lt;/span&gt;&lt;span style="color: blue"&gt;let rec &lt;/span&gt;filesUnder rootPath =
    seq {
        &lt;span style="color: blue"&gt;for &lt;/span&gt;file &lt;span style="color: blue"&gt;in &lt;/span&gt;Directory.GetFiles(rootPath) &lt;span style="color: blue"&gt;do
            yield &lt;/span&gt;file
        &lt;span style="color: blue"&gt;for &lt;/span&gt;dir &lt;span style="color: blue"&gt;in &lt;/span&gt;Directory.GetDirectories(rootPath) &lt;span style="color: blue"&gt;do
            yield! &lt;/span&gt;filesUnder dir }
            
            
&lt;span style="color: green"&gt;// Deletes all files
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;deleteAll files = Seq.iter File.Delete files

&lt;span style="color: green"&gt;// Notice just how flippin sweet type inference is...
// File.Delete : string -&amp;gt; unit
// Seq.iter    : ('a -&amp;gt; unit) -&amp;gt; #seq&amp;lt;'a&amp;gt; -&amp;gt; unit
// deleteAll   : #seq&amp;lt;string&amp;gt; -&amp;gt; unit

// The pipe-backwards operator allows you to get this to
// execute in the right order without parens around 'filesUnder'
&lt;/span&gt;deleteAll &amp;lt;| filesUnder &lt;span style="color: maroon"&gt;@&amp;quot;C:\Logs&amp;quot;
&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8639859" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/ChrisSmithsCompletelyUniqueView/~4/317698511" height="1" width="1"/&gt;</description><category domain="http://blogs.msdn.com/chrsmith/archive/tags/F_2300_/default.aspx">F#</category><category domain="http://blogs.msdn.com/chrsmith/archive/tags/Scripting/default.aspx">Scripting</category><category domain="http://blogs.msdn.com/chrsmith/archive/tags/Shameless+Plugs/default.aspx">Shameless Plugs</category><feedburner:origLink>http://blogs.msdn.com/chrsmith/archive/2008/06/22/shameless-plug-fstest.aspx</feedburner:origLink></item><item><title>Function Composition</title><link>http://feeds.feedburner.com/~r/ChrisSmithsCompletelyUniqueView/~3/311937602/function-composition.aspx</link><pubDate>Sat, 14 Jun 2008 16:25:03 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8597844</guid><dc:creator>ChrSmith</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/chrsmith/comments/8597844.aspx</comments><wfw:commentRss>http://blogs.msdn.com/chrsmith/commentrss.aspx?PostID=8597844</wfw:commentRss><description>&lt;p&gt;During a lunchtime conversation with Dustin Cambell, of &lt;a href="http://diditwith.net/"&gt;Did it with .NET&lt;/a&gt; fame, the topic of Function Composition came up. I am a huge fan of the pipe-forward operator (|&amp;gt;) but have never found a use for the function composition operator (&amp;gt;&amp;gt;). Dustin pointed me to his latest blog post and after reading it, realized the error of my ways. Function Composition is one of those those foundational skills that you should definitely try to master in F#.&lt;/p&gt;  &lt;p&gt;So what is Function Composition? Function Composition is composing new, more powerful functions based on smaller ones. Let’s say your task is to compute the size on disk of all the files under a certain path and you have the following helper routines:&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Basic Functions&lt;/strong&gt;&lt;/p&gt;  &lt;pre class="code"&gt;#light

&lt;span style="color: blue"&gt;open &lt;/span&gt;System
&lt;span style="color: blue"&gt;open &lt;/span&gt;System.IO

&lt;span style="color: green"&gt;// Gets all files under a given folder
&lt;/span&gt;&lt;span style="color: blue"&gt;let rec &lt;/span&gt;filesUnderFolder rootFolder = 
    seq {
        &lt;span style="color: blue"&gt;for &lt;/span&gt;file &lt;span style="color: blue"&gt;in &lt;/span&gt;Directory.GetFiles(rootFolder) &lt;span style="color: blue"&gt;do
            yield &lt;/span&gt;file
        &lt;span style="color: blue"&gt;for &lt;/span&gt;dir &lt;span style="color: blue"&gt;in &lt;/span&gt;Directory.GetDirectories(rootFolder) &lt;span style="color: blue"&gt;do
            yield! &lt;/span&gt;filesUnderFolder dir }

&lt;span style="color: green"&gt;// Gets the information about a file
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;fileInfo filename = &lt;span style="color: blue"&gt;new &lt;/span&gt;FileInfo(filename)

&lt;span style="color: green"&gt;// Gets the file size from a FileInfo object
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;fileSize (fileinfo : FileInfo) = fileinfo.Length

&lt;span style="color: green"&gt;// Converts a byte count to MB
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;bytesToMB (bytes : Int64) = bytes / (1024L * 1024L)&lt;/pre&gt;

&lt;p&gt;The old-fashioned, imperative programming way of calculating the result would be to call each function in sequence, store the result, and pass it into the next function.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lame, Imperative Code&lt;/strong&gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Doing things the lame way
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;photosInMB_lame =
    &lt;span style="color: blue"&gt;let &lt;/span&gt;folder = &lt;span style="color: #a31515"&gt;@&amp;quot;C:\Users\chrsmith\Pictures\&amp;quot;
    &lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;filesInFolder = filesUnderFolder folder
    &lt;span style="color: blue"&gt;let &lt;/span&gt;fileInfos     = Seq.map fileInfo filesInFolder
    &lt;span style="color: blue"&gt;let &lt;/span&gt;fileSizes     = Seq.map fileSize fileInfos
    &lt;span style="color: blue"&gt;let &lt;/span&gt;totalSize     = Seq.fold (+) 0L fileSizes
    &lt;span style="color: blue"&gt;let &lt;/span&gt;fileSizeInMB  = bytesToMB totalSize
    fileSizeInMB&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;We can improve upon this by using the pipe-forward operator (|&amp;gt;) which is defined as:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let inline &lt;/span&gt;(|&amp;gt;) x f = f x&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The pipe-forward operator allows you to rearrange the ordering of a function so that the argument comes before the function. Using this then, you can ‘pipe’ multiple functions together and avoid the need for temporary variables. So here we take the file path and pipe it to the ‘filesUnderFolder’ function, then pipe the sequence of files to ‘Seq.map fileInfo’, then pipe that result to ‘Seq.map fileSize’, and so on.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Better, Using Pipe-Forward Operator&lt;/strong&gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Using the Pipe-Forward operator (|&amp;gt;)
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;photosInMB_pipeforward =
    &lt;span style="color: #a31515"&gt;@&amp;quot;C:\Users\chrsmith\Pictures\&amp;quot;
    &lt;/span&gt;|&amp;gt; filesUnderFolder
    |&amp;gt; Seq.map fileInfo
    |&amp;gt; Seq.map fileSize
    |&amp;gt; Seq.fold (+) 0L 
    |&amp;gt; bytesToMB&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;The solution using the pipe-forward operator is pretty elegant. But it contains a subtle problem in that you need to provide the initial argument to begin the piping process. So in order to reuse this code you need something like:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// A reusable function using Piping
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;photosInMB_reusable baseFolder =
    baseFolder
    |&amp;gt; filesUnderFolder
    |&amp;gt; Seq.map fileInfo
    |&amp;gt; Seq.map fileSize
    |&amp;gt; Seq.fold (+) 0L 
    |&amp;gt; bytesToMB&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;And to be honest, that’s the way I’ve been writing a lot of code lately. Create a function that takes an argument and then pass that argument into a series of piped-functions back to back. But alas, there is a better way!&lt;/p&gt;

&lt;p&gt;Introducing the Function Composition operator (&amp;gt;&amp;gt;):&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let inline &lt;/span&gt;(&amp;gt;&amp;gt;) f g x = g(f x)&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Which reads as: given two functions, f and g, and a value, x, compute the result of f of x and pass that result to g. The interesting thing here is that you can curry the (&amp;gt;&amp;gt;) function and only pass in parameters f and g, the result is a function which takes a single parameter and produces the result g ( f ( x ) ).&lt;/p&gt;

&lt;p&gt;Here's a quick example of composing a function out of smaller ones:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;negate x = x * -1
&lt;span style="color: blue"&gt;let &lt;/span&gt;square x = x * x
&lt;span style="color: blue"&gt;let &lt;/span&gt;print  x = printfn &lt;span style="color: #a31515"&gt;&amp;quot;The number is: %d&amp;quot; &lt;/span&gt;x

&lt;span style="color: blue"&gt;let &lt;/span&gt;square_negate_then_print = square &amp;gt;&amp;gt; negate &amp;gt;&amp;gt; print&lt;br /&gt;&lt;span style="color: blue"&gt;asserdo &lt;/span&gt;square_negate_then_print 2&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Which when executed prints ‘-4’. We have successfully joined several functions together, like we did using (|&amp;gt;) but we didn’t need to declare a parameter and pass that to our function chain. Instead we rely on a partial application of (&amp;gt;&amp;gt;). We can now rewrite our original directory crawler using function composition:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Using the Function-Composition operator (&amp;gt;&amp;gt;)
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;getFolderSize = 
    filesUnderFolder 
    &amp;gt;&amp;gt; Seq.map fileInfo 
    &amp;gt;&amp;gt; Seq.map fileSize 
    &amp;gt;&amp;gt; Seq.fold (+) 0L 
    &amp;gt;&amp;gt; bytesToMB&lt;br /&gt;&lt;/pre&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;photosInMB_funccomp = getFolderSize &lt;span style="color: #a31515"&gt;@&amp;quot;C:\Users\chrsmith\Pictures\&amp;quot;&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Think of function composition (&amp;gt;&amp;gt;) just like using pipe-forward (|&amp;gt;) except you don’t need to specify the first parameter up front. Using (&amp;gt;&amp;gt;) will allow for slightly more concise code and provide a new way to think about applying your functions.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8597844" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/ChrisSmithsCompletelyUniqueView/~4/311937602" height="1" width="1"/&gt;</description><category domain="http://blogs.msdn.com/chrsmith/archive/tags/F_2300_/default.aspx">F#</category><feedburner:origLink>http://blogs.msdn.com/chrsmith/archive/2008/06/14/function-composition.aspx</feedburner:origLink></item><item><title>Language Oriented Programming in F#</title><link>http://feeds.feedburner.com/~r/ChrisSmithsCompletelyUniqueView/~3/301450466/language-oriented-programming-in-f.aspx</link><pubDate>Fri, 30 May 2008 19:16:04 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8564036</guid><dc:creator>ChrSmith</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/chrsmith/comments/8564036.aspx</comments><wfw:commentRss>http://blogs.msdn.com/chrsmith/commentrss.aspx?PostID=8564036</wfw:commentRss><description>&lt;p&gt;Last Tuesday I gave a talk to the &lt;a href="http://www.netda.net/"&gt;.NET Developers Association&lt;/a&gt; entitled &lt;em&gt;Language Oriented Programming in F#&lt;/em&gt;. You can find a video of the presentation &lt;a href="http://www.youtube.com/watch?v=eBGIQ7ZuuiU"&gt;here&lt;/a&gt;*. This essay is the written version of that presentation, which unfortunately doesn’t translate to the web so well. In fact, I’m going to go ahead and apologize now for this crazy-long post.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;h3&gt;What is Language Oriented Programming&lt;/h3&gt; &lt;p&gt;Let me start by saying that Language Oriented Programing (LOP) is a nebulous term, like meta-programming. Rather than trying to pin it down concretely, I’ll define it in broad terms and then provide many examples. &lt;/p&gt; &lt;p&gt;To understand what LOP is first you must understand the concept of a Domain Specific Language or DSL. A DSL is a programming language designed to solve problems within a narrowly-defined problem domain. (Opposed to a General Purpose programming language, like C# or F#, which can solve problems in any domain.) An example of a DSL would be Excel. To write a formula that adds the contents of two cells you write “= A1 + B1”, no need for defining data types, functions, conversion routines, etc. The Excel language has the concept of a spreadsheet cell baked into the language, so you don’t need to describe what ‘A1’ means in terms of anything else. In C# on the other hand, you can’t write ‘A1’ you need to write something like “MasterSheet.GetCell(new CellObject(Row = “A”, Column = 1));”.&lt;/p&gt; &lt;p&gt;The main advantage of a DSL is that the code is always much simpler than its general purpose programming language counterpart. With a DSL you don’t need to write the ‘scaffolding’ you normally would in order to express your ideas, since all the key concepts of the problem domain are baked into the language.&lt;/p&gt; &lt;p&gt;DSLs have two major drawbacks however. First, DSLs force you to learn a new language. Second, somebody needs to define that language and build the compiler for it.&amp;nbsp; For simple problem domains these drawbacks aren’t much of a problem. But if you wanted your DSL do describe the business rules for your entire company however, then you can see how DSLs fail to scale. If you are interested in building DSLs however &lt;a href="http://msdn.microsoft.com/en-us/library/bb126235(VS.80).aspx"&gt;Toolkits&lt;/a&gt; do exist.&lt;/p&gt; &lt;p&gt;So what is LOP then? To provide a great example, let me introduce a project called &lt;a href="http://code.google.com/p/fsunit/"&gt;FsUnit&lt;/a&gt; over on Google code. It is a simple library for writing Unit Tests in F#, but rather than the standard ‘Assert.IsTrue(x)’ you can write:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Equality
&lt;/span&gt;1 |&amp;gt; should (equal 1)

&lt;span style="color: green"&gt;// Checking existence in a collection
&lt;/span&gt;[| &lt;span style="color: #a31515"&gt;"item1" &lt;/span&gt;|] |&amp;gt; should (contain &lt;span style="color: #a31515"&gt;"item1"&lt;/span&gt;)
[| &lt;span style="color: #a31515"&gt;"item1" &lt;/span&gt;|] |&amp;gt; should (notContain &lt;span style="color: #a31515"&gt;"item2"&lt;/span&gt;)

&lt;span style="color: green"&gt;// Size of a collection
&lt;/span&gt;personList |&amp;gt; should (have 4 &lt;span style="color: #a31515"&gt;"people"&lt;/span&gt;)Some text matches a regular expression: 

&lt;span style="color: green"&gt;// RegEx patterns
&lt;/span&gt;&lt;span style="color: #a31515"&gt;"test infected" &lt;/span&gt;|&amp;gt; should (matchThePattern &lt;span style="color: #a31515"&gt;"inf"&lt;/span&gt;)

&lt;span style="color: green"&gt;// Other primitives
&lt;/span&gt;&lt;span style="color: blue"&gt;true &lt;/span&gt;|&amp;gt; should (be True)
&lt;span style="color: blue"&gt;false &lt;/span&gt;|&amp;gt; should (notBe True)
&lt;span style="color: #a31515"&gt;"" &lt;/span&gt;|&amp;gt; should (be Empty)
&lt;span style="color: #a31515"&gt;"a string" &lt;/span&gt;|&amp;gt; should (notBe Empty)
&lt;span style="color: blue"&gt;null &lt;/span&gt;|&amp;gt; should (be Null)
anObj |&amp;gt; should (notBe Null)&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;FsUnit allows you to write F# code, but using words and concepts in a different language. (In this case, English.) Armed with this example I will define what LOP is: &lt;strong&gt;Language Oriented Programming is a style of programming that tries to produce code that looks like it came from a Domain Specific Language but is still valid in a general purpose programming language&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The rest of this essay will provide examples of LOP in F# and how using LOP results in simpler code that better expresses the problem at hand. I’ll my examples along three major themes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Abstract Representation.&amp;nbsp; Features in F# that allow you to represent domain-specific concepts in your F# code without needing to introduce a new layer of abstraction. 
&lt;li&gt;Concrete Representation. Features in F# that allow you to describe your problem in another language and load that into F#. 
&lt;li&gt;Computational Representation. Finally I’ll go into features in F# that enable you to write code to process concepts in some other language without resorting to a third, more specialized language. &lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;&lt;strong&gt;Part I – Abstract Representation&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;One problem facing programmers using modern Object Oriented languages is how to represent concepts in their language. C# only has facilities to express concepts in terms of objects and their behaviors, which makes it difficult to accurately express abstract ideas. Having a class for ‘Cat’ with methods Meow() and Purr() makes sense. But how would you write the concept of ‘Happiness’ in C#? Would there be methods ‘CheerSomethingUp(object thing)’?&lt;/p&gt;
&lt;p&gt;By Abstract Representation I’m talking about the ability to represent concepts in your F# code as naturally as possible.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Type Abbreviations&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="color: blue"&gt;&lt;font color="#000000"&gt;The first feature I'll go into is Type Abbreviations. In F# you have the ability to create an alias for another type, which at compile time will be replaced with the underlying core type. Meaning that type abbreviations only exist at design-time. Using Type Abbreviations you can write code in terms of problem-domain concepts without needing to introduce custom types. For example I'll create a type alias for 'int' called CustomerID. Now if I write a function that takes type CustomerID I know exactly what it expects, rather than a function taking type 'int’ and me needing to guess at what that integer represents.&lt;/font&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;CustomerID = int &lt;br&gt;&lt;br&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;alice = 98123 &lt;br&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;bob&amp;nbsp;&amp;nbsp; = 78435 : CustomerID &lt;br&gt;&lt;br&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;span style="color: green"&gt;// With the type annotation the value 'customer' appears as to &lt;br&gt;// have type 'CustomerID' but at compile time that is replaced &lt;br&gt;// with 'int'. You can pass both alice and bob to function &lt;br&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;span style="color: green"&gt;// getCustomerOrders. &lt;br&gt;&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;getCustomerOrders (customer : CustomerID) = &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; printfn &lt;span style="color: #a31515"&gt;"%d has ordered 5 items."&lt;/span&gt;customer&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Type abbreviations are especially helpful when you are dealing with more complex generic types. Consider &lt;font face="Courier New"&gt;Dictionary&amp;lt;string, string&amp;gt;&lt;/font&gt;. It has some use, but from just the type signature you have no idea what the key, value pairs correspond to. But with type abbreviations you can call it something more meaningful.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;open &lt;/span&gt;System.Collections.Generic
&lt;span style="color: blue"&gt;type &lt;/span&gt;TeamCityLookup = Dictionary&amp;lt;string, string&amp;gt;

&lt;span style="color: green"&gt;// A TeamCityLoop is a better description for the type than Dictionary&amp;lt;string, string&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;teamLookup = &lt;span style="color: blue"&gt;new &lt;/span&gt;TeamCityLookup()
teamLookup.Add(&lt;span style="color: #a31515"&gt;"Mariners"&lt;/span&gt;, &lt;span style="color: #a31515"&gt;"Seattle"&lt;/span&gt;)
teamLookup.Add(&lt;span style="color: #a31515"&gt;"Reds"&lt;/span&gt;,     &lt;span style="color: #a31515"&gt;"Cincinati"&lt;/span&gt;)
teamLookup.Add(&lt;span style="color: #a31515"&gt;"Dodgers"&lt;/span&gt;,  &lt;span style="color: #a31515"&gt;"Los Angeles"&lt;/span&gt;)

teamLookup.[&lt;span style="color: #a31515"&gt;"Mariners"&lt;/span&gt;]&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;/strong&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Discriminated Unions&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Consider the following C# code used to express the concept of a card suit.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;enum &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CardSuit
&lt;/span&gt;{
    Club,
    Spade,
    Diamond,
    Heart
}&lt;/pre&gt;
&lt;p&gt;While the code looks simple and clear, it actually introduces many problems because enumerations alone aren't sufficient for expressing the idea of a mutually-exclusive set of values. It is easy to write C# code that violates the principle that a card can only have one possible suit.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;CardSuit &lt;/span&gt;invalid1 = &lt;span style="color: #2b91af"&gt;CardSuit&lt;/span&gt;.Club | &lt;span style="color: #2b91af"&gt;CardSuit&lt;/span&gt;.Heart;
&lt;span style="color: #2b91af"&gt;CardSuit &lt;/span&gt;invalid2 = (&lt;span style="color: #2b91af"&gt;CardSuit&lt;/span&gt;) (-1);&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;In order to write the concept of a card suit in C# you need to write some slightly more complex code. You can see how in chapter 21 of &lt;em&gt;&lt;a href="http://java.sun.com/docs/books/effective/"&gt;Effective Java&lt;/a&gt;&lt;/em&gt;. In F# though, you can express this concept without any fuss.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;Suit = 
    | Diamonds 
    | Hearts
    | Spades 
    | Clubs

&lt;span style="color: green"&gt;// An instance of 'Suit' can only have one of four possible values
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;printSuitName suit =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;suit &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| Diamonds &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"Suit is a Diamond"
    &lt;/span&gt;| Hearts   &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"Suit is a Heart"
    &lt;/span&gt;| Spades   &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"Suit is a Spade"
    &lt;/span&gt;| Clubs    &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"Suit is a Club"&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Moreover, in F# Discriminated Unions can also attach data making them much more powerful than enumerations without sacrificing any of their ease of definition.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Discriminated Unions can hold data too!
&lt;/span&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;Card =
    | ValueCard &lt;span style="color: blue"&gt;of &lt;/span&gt;int * Suit  &lt;span style="color: green"&gt;// Value 2 - 10 and Suit
    &lt;/span&gt;| Jack      &lt;span style="color: blue"&gt;of &lt;/span&gt;Suit
    | Queen     &lt;span style="color: blue"&gt;of &lt;/span&gt;Suit
    | King      &lt;span style="color: blue"&gt;of &lt;/span&gt;Suit
    | Ace       &lt;span style="color: blue"&gt;of &lt;/span&gt;Suit
    | Joker
    
&lt;span style="color: green"&gt;// Simple syntax for defining instances of Disc Unions
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;myPokerHand = 
    [ 
        ValueCard(2, Hearts) 
        ValueCard(5, Spades) 
        Joker                
        ValueCard(4, Clubs)  
        Ace(Clubs)
     ]&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Option Type&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Sorry to rag on C# some more, but here’s another instance where .NET adds confusion where there shouldn’t be. Consider the following code where I get an instance of your pet and print its name if you have one.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;Pet &lt;/span&gt;yourPet = you.GetPet();&lt;br&gt;
&lt;span style="color: blue"&gt;if &lt;/span&gt;(yourPet != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;"You have pet named " &lt;/span&gt;+ yourPet.Name);&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;The code looks simple enough. But where in the real world does &lt;span style="color: blue"&gt;null &lt;/span&gt;exist? Is that in the problem domain? If I asked you if you had a pet wombat would you say ‘null’? No, null is an artifact of the programming language used to represent the absence of something or an uninitialized value. But in LOP we are trying to represent ideas without any overhead. F# has the option type that will represent the concept of nothing in a more natural way.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;Pet =
    | GoldFish
    | Dog
    | Cat
    
&lt;span style="color: green"&gt;// Takes a 'Person' type and returns an option, of their pet type
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;getPetType person =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;person &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| Me           &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;Some(Dog)
    | SomebodyElse &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;Some(GoldFish)
    | You          &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;None&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;If you have a pet Some(…) is returned, meaning there is something. If you don’t have a pet you return None. Another big advantage to the option type is that it communicates intent. If you call the ‘GetPet’ method in C#, it is unclear what the result will be if you don’t have a pet. Will the method throw an exception or simply return null? In F# using the option type means that it will return None should you not have a pet.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;/strong&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Pattern Matching&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Pattern matching is another way we can express what we mean clearly in code. In C# you can use a &lt;span style="color: blue"&gt;switch &lt;/span&gt;statement, but that only works on constant values. In F# however, Pattern Matching can do much more than compare a value against a constant. It can, for example, compare against the structure of the data. Here we match against the length of a list:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Structure of data
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;shortList = ['a'; 'b'; 'c']

&lt;span style="color: blue"&gt;let &lt;/span&gt;printListLength list =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;list &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| []      &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"List is empty"
    &lt;/span&gt;| [_]     &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"List has 1 element"
    &lt;/span&gt;| [_;_]   &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"List has 2 elements"
    &lt;/span&gt;| [_;_;_] &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"List has 3 elements"
    &lt;/span&gt;| _       &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"List too long"&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;In addition, Pattern Matching can also capture variables as part of the match.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Match contants and capture variables
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;sayHello (first, last) =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;(first, last) &lt;span style="color: blue"&gt;with
    &lt;/span&gt;&lt;span style="color: green"&gt;// Match constants
    &lt;/span&gt;| &lt;span style="color: #a31515"&gt;"Bill"&lt;/span&gt;, &lt;span style="color: #a31515"&gt;"Gates"
    &lt;/span&gt;| &lt;span style="color: #a31515"&gt;"Steve"&lt;/span&gt;, &lt;span style="color: #a31515"&gt;"Balmer"
        &lt;/span&gt;&lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"Steve and Bill, wazzzup!"
    
    &lt;/span&gt;&lt;span style="color: green"&gt;// Match first against constant, capture second
    &lt;/span&gt;| &lt;span style="color: #a31515"&gt;"Chris"&lt;/span&gt;, last
        &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"Hello Chris. Your last name is %s" &lt;/span&gt;last
    
    &lt;span style="color: green"&gt;// Capture both values
    &lt;/span&gt;| first, last
        &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"Hello %s %s" &lt;/span&gt;first last&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Demo&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Now that we have the building blocks to represent ideas in F#, we have all the power we need to represent a real world problem in the language of mathematics.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// This Discriminated Union is sufficient to express any four-function
// mathematical expression.
&lt;/span&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;Expr =
    | Num      &lt;span style="color: blue"&gt;of &lt;/span&gt;int
    | Add      &lt;span style="color: blue"&gt;of &lt;/span&gt;Expr * Expr
    | Subtract &lt;span style="color: blue"&gt;of &lt;/span&gt;Expr * Expr
    | Multiply &lt;span style="color: blue"&gt;of &lt;/span&gt;Expr * Expr
    | Divide   &lt;span style="color: blue"&gt;of &lt;/span&gt;Expr * Expr
    
&lt;span style="color: green"&gt;// This simple pattern match is all we need to evaluate those
// expressions. 
&lt;/span&gt;&lt;span style="color: blue"&gt;let rec &lt;/span&gt;evaluate expr =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;expr &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| Num(x)             &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;x
    | Add(lhs, rhs)      &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;(evaluate lhs) + (evaluate rhs)
    | Subtract(lhs, rhs) &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;(evaluate lhs) - (evaluate rhs)
    | Multiply(lhs, rhs) &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;(evaluate lhs) * (evaluate rhs)
    | Divide(lhs, rhs)   &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;(evaluate lhs) / (evaluate rhs)

&lt;span style="color: green"&gt;// 10 * 10 - 25 / 5
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;sampleExpr = 
    Subtract(
        Multiply(
            Num(10), 
            Num(10)),
        Divide(
            Num(25), 
            Num(5)))
        
&lt;span style="color: blue"&gt;let &lt;/span&gt;result = evaluate sampleExpr&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;In this simple example we were able to represent and evaluate a four-function mathematical expression using only a discriminated union and a pattern match. You would be hard pressed to write the equivalent C# in as few lines of code because you would need to add additional scaffolding to represent these concepts. &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;&lt;strong&gt;Part II – Concrete Representation&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;Concrete Representation means expressing your problem conceretely in another language and loading that into your F# program. By allowing you to work in both your Domain Specific Language and F#, you can express your problem in specific terms and then do any processing required in F#.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;/strong&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;fslex and fsyacc&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The simplest way to deal with a concrete representation of another language is to build a parser and ‘load it’ just like a compiler. Lex and Yacc have been standard tools for generating parsers for thirty years. FsLex and FsYacc are implementations of Lex and Yacc that generate F# parsers. I won’t go into too much deal here, but if you are interested in learning more refer to my previous &lt;a href="http://blogs.msdn.com/chrsmith/archive/2008/01/18/fslex-Sample.aspx"&gt;blog post&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Lex and Yacc are DSLs for describing compiler parsers and lexers, or tools which break down ‘source’ into a series of tokens and then convert that token stream into an Abstract Syntax Tree. For example, here is the Lex code for converting a string like “10 * 8 + 5.0” into tokens [INT32(10); ASTER; INT32(8); PLUS; FLOAT(5.0)]&lt;/p&gt;&lt;pre class="code"&gt;rule tokenize = parse
| whitespace    { tokenize lexbuf }
| newline       { tokenize lexbuf }
&lt;span style="color: green"&gt;// Operators
&lt;/span&gt;| &lt;span style="color: #a31515"&gt;"+"            &lt;/span&gt;{ PLUS }
| &lt;span style="color: #a31515"&gt;"-"            &lt;/span&gt;{ MINUS }
| &lt;span style="color: #a31515"&gt;"*"            &lt;/span&gt;{ ASTER }
| &lt;span style="color: #a31515"&gt;"/"            &lt;/span&gt;{ SLASH }
&lt;span style="color: green"&gt;// Numberic constants
&lt;/span&gt;| ['-']?digit+  { INT32 (Int32.Parse(lexeme lexbuf)) }
| ['-']?digit+('.'digit+)?(['e''E']digit+)?   { FLOAT (Double.Parse(lexeme lexbuf)) }
| eof   { EOF }&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;The corresponding Yacc parser file would look something like this, which would match tokens against grammar productions and create AST nodes.&lt;/p&gt;&lt;pre class="code"&gt;Prog:
    | Expr EOF                  { $1 }

Expr: 
    | Expr PLUS Term            { Plus($1, $3) }
    | Expr MINUS Term           { Minus($1, $3) }
    | Term                      { Term($1) }

Term:
    | Term ASTER Factor         { Times($1, $3) }
    | Term SLASH Factor         { Divide($1, $3) }
    | Factor                    { Factor($1) }

Factor:
    | FLOAT                     { Float($1) }
    | INT32                     { Integer($1) }&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;If none of this Lex and Yacc jazz made sense to you don’t worry. The point is that if you wanted to, there are tools available that will allow you to write F# programs that can parse &lt;strong&gt;any other language you want&lt;/strong&gt;. So if you wanted to write a parser for all mathematical equations (“1^5 + cos(PI)”) you could. If you wanted to parse structured log files, you could. If you wanted to write a parser for F# code so&amp;nbsp; you could manipulate it in an F# program, you could. With fslex and fsyacc you can write a parser for any domain specific language you want, and load its abstract representation into your F# program.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;/strong&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Active Patterns&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The next feature I’ll talk about which allows you to convert a concrete representation of a language into F# is Active Patterns. (Which&lt;a href="http://blogs.msdn.com/chrsmith/archive/2008/02/21/Introduction-to-F_2300_-Active-Patterns.aspx"&gt;I’ve blogged about this before&lt;/a&gt;.) The easiest way to think about Active Patterns is that they are a way to convert data from one representation to another, typically via a pattern matching. &lt;/p&gt;
&lt;p&gt;Active Patterns come in three main flavors: single-case, multi-case, and partial.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;strong&gt;Single-case Active Patterns&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Single-case Active Patterns take an input of one type of data and convert it into something else. In the following example we convert strings to integers. Notice the result of the Active Pattern is at the end of the 'match clause’.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// SingleCase Active Patterns

// Covnert a string to an int
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;(|IntValue|) input = Int32.Parse(input)

&lt;span style="color: green"&gt;// Given a string print its integer representation.
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;printValue (str : string) =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;str &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| IntValue 0 &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"str is zero"
    &lt;/span&gt;| IntValue 1 &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"str is one"
    &lt;/span&gt;| IntValue 2 &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"str is two"
    
    &lt;/span&gt;&lt;span style="color: green"&gt;// Variable capture of AP output
    &lt;/span&gt;| IntValue x &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"str is %d" &lt;/span&gt;x&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;&lt;strong&gt;Multi-case active Patterns&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Multi-case Active Patterns convert the input into one of several types of output, dividing the input space into several regions. For example, we can convert an integer into one of three categories: Odd, Even, or Zero. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Multi-Case Active Patterns
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;(|Even|Odd|Zero|) x =
    &lt;span style="color: blue"&gt;if &lt;/span&gt;x = 0       &lt;span style="color: blue"&gt;then &lt;/span&gt;Zero
    &lt;span style="color: blue"&gt;elif &lt;/span&gt;x % 2 = 0 &lt;span style="color: blue"&gt;then &lt;/span&gt;Even
    &lt;span style="color: blue"&gt;else                &lt;/span&gt;Odd

&lt;span style="color: green"&gt;// Takes an int and prints its status
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;printStatus x =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;x &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| Zero &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"%d is zero" &lt;/span&gt;x
    | Even &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"%d is even" &lt;/span&gt;x
    | Odd  &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"%d is odd " &lt;/span&gt;x&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;&lt;strong&gt;Partial Active Patterns&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="color: green"&gt;&lt;font color="#000000"&gt;Partial Active Patterns are just like Single-case Active Patterns, but they don’t always succeede. In our previous example we converted strings to integers, but a string cannot always be converted into an integer. For example “foo”. Partial Active Patterns use Option types to represent whether or not the data was convertered. Here we will convert strings into either Integers or Floating point numbers.&lt;/font&gt;&lt;/span&gt;&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Partial Active Pattern
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;(|ToInt|_|) str = 
    &lt;span style="color: blue"&gt;let &lt;/span&gt;(parsed, result) = Int32.TryParse(str)
    &lt;span style="color: blue"&gt;if &lt;/span&gt;parsed &lt;span style="color: blue"&gt;then &lt;/span&gt;Some(result)
    &lt;span style="color: blue"&gt;else           &lt;/span&gt;None

&lt;span style="color: blue"&gt;let &lt;/span&gt;(|ToFloat|_|) str = 
    &lt;span style="color: blue"&gt;let &lt;/span&gt;(parsed, result) = Single.TryParse(str)
    &lt;span style="color: blue"&gt;if &lt;/span&gt;parsed &lt;span style="color: blue"&gt;then &lt;/span&gt;Some(result)
    &lt;span style="color: blue"&gt;else           &lt;/span&gt;None

&lt;span style="color: green"&gt;// Takes a string and prints whether it is an int or float
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;parseValue str =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;str &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| ToInt   x &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"str is an int with value %d" &lt;/span&gt;x
    | ToFloat x &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"str is a float with value %f" &lt;/span&gt;x
    | _         &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"str is neither an int nor a float"&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;&lt;strong&gt;Demo&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Here is an example of how you can leverage Active Patterns to convert a concrete representation of a language into F#. The example is from a demo from a research paper by &lt;a href="http://blogs.msdn.com/dsyme/archive/2007/04/07/draft-paper-on-f-active-patterns.aspx"&gt;Don Syme, Margetson and Gregory Neverov&lt;/a&gt; which introduced the concept of Active Patterns. Since code is really complicated, but I’ll just point out the black magic. Given this XML doc we can extract all meaningful information from it, that is attributes and nested elements, &lt;em&gt;in&lt;/em&gt; &lt;em&gt;just one line of code&lt;/em&gt;.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Concrete language
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;xmlDoc = 
    &lt;span style="color: blue"&gt;let &lt;/span&gt;temp = &lt;span style="color: blue"&gt;new &lt;/span&gt;System.Xml.XmlDocument()  
    &lt;span style="color: blue"&gt;let &lt;/span&gt;superHerosXmlDoc = 
        &lt;span style="color: #a31515"&gt;"&amp;lt;?xml version=\"1.0\" encoding=\"utf-8\"?&amp;gt;
        &amp;lt;Scene&amp;gt;
            &amp;lt;Sphere r='3' x='4' y='3' z='0' /&amp;gt;
            &amp;lt;Intersect&amp;gt;
                &amp;lt;Sphere r='2' x='1' y='0' z='0'/&amp;gt;
                &amp;lt;Intersect&amp;gt;
                    &amp;lt;Sphere r='2' x='4' y='0' z='0'/&amp;gt;
                    &amp;lt;Cube d='1' x='6' y='7' z='8' /&amp;gt;
                    &amp;lt;Sphere r='2' x='-3' y='0' z='0'/&amp;gt;
                &amp;lt;/Intersect&amp;gt;
                &amp;lt;Cube d='2' x='-2' y='1' z='0'/&amp;gt;
            &amp;lt;/Intersect&amp;gt;
        &amp;lt;/Scene&amp;gt;
        "
    &lt;/span&gt;temp.LoadXml(superHerosXmlDoc)
    temp

&lt;span style="color: green"&gt;// Abstract representation
&lt;/span&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;GeometricScene =
| Cube      &lt;span style="color: blue"&gt;of &lt;/span&gt;float * float * float * float
| Sphere    &lt;span style="color: blue"&gt;of &lt;/span&gt;float * float * float * float
| Intersect &lt;span style="color: blue"&gt;of &lt;/span&gt;GeometricScene list

&lt;span style="color: green"&gt;// Mach an XML element
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;(|Elem|_|) name (inp: #XmlNode) =
    &lt;span style="color: blue"&gt;if &lt;/span&gt;inp.Name = name &lt;span style="color: blue"&gt;then &lt;/span&gt;Some(inp)
    &lt;span style="color: blue"&gt;else                    &lt;/span&gt;None

&lt;span style="color: green"&gt;// Get the attributes of an element
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;(|Attributes|) (inp: #XmlNode) = inp.Attributes

&lt;span style="color: green"&gt;// Match a specific attribute
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;(|Attr|) attrName (inp: XmlAttributeCollection) =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;inp.GetNamedItem(attrName) &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| &lt;span style="color: blue"&gt;null -&amp;gt; &lt;/span&gt;failwith (attrName + &lt;span style="color: #a31515"&gt;" not found"&lt;/span&gt;)
    | attr &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;attr.Value

&lt;span style="color: green"&gt;// Convert a string to a float
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;(|Float|) s = Float.of_string s

&lt;span style="color: green"&gt;// Parses a vector out of an attribute collection
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;(|Vector|) inp =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;inp &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| (Attr &lt;span style="color: #a31515"&gt;"x" &lt;/span&gt;(Float x) &amp;amp; 
       Attr &lt;span style="color: #a31515"&gt;"y" &lt;/span&gt;(Float y) &amp;amp; 
       Attr &lt;span style="color: #a31515"&gt;"z" &lt;/span&gt;(Float z)) 
        &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;(x,y,z)

&lt;span style="color: green"&gt;// Parses a GeometricScene from an XML node
&lt;/span&gt;&lt;span style="color: blue"&gt;let rec &lt;/span&gt;(|ShapeElem|_|) inp =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;inp &lt;span style="color: blue"&gt;with
    &lt;/span&gt;&lt;span style="color: green"&gt;// By using nested Active Patterns we can parse all attributes on one line!
    // (Attributes (Attr "r" (Float r))) gets the Attributes of the node, then gets
    // the attribute "r", then finally converts its string value into a float.
    &lt;/span&gt;| Elem &lt;span style="color: #a31515"&gt;"Sphere" &lt;/span&gt;(Attributes (Attr &lt;span style="color: #a31515"&gt;"r" &lt;/span&gt;(Float r) &amp;amp; Vector (x,y,z)))
        &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;Some (Sphere (r,x,y,z))
    
    | Elem &lt;span style="color: #a31515"&gt;"Intersect" &lt;/span&gt;(ShapeElems(objs))
        &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;Some (Intersect objs)
    
    &lt;span style="color: green"&gt;// This is what the cde would look like without nested Active Patterns
    &lt;/span&gt;| Elem &lt;span style="color: #a31515"&gt;"Cube" &lt;/span&gt;xmlElement
        &lt;span style="color: blue"&gt;-&amp;gt; match &lt;/span&gt;xmlElement &lt;span style="color: blue"&gt;with
           &lt;/span&gt;| Attributes xmlElementsAttributes 
               &lt;span style="color: blue"&gt;-&amp;gt; match &lt;/span&gt;xmlElementsAttributes &lt;span style="color: blue"&gt;with
                  &lt;/span&gt;| Attr &lt;span style="color: #a31515"&gt;"d" &lt;/span&gt;dAttrib &amp;amp; Vector (x, y, z)
                      &lt;span style="color: blue"&gt;-&amp;gt; match &lt;/span&gt;dAttrib &lt;span style="color: blue"&gt;with
                         &lt;/span&gt;| Float d &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;Some(Cube(d, x, y, z))

    &lt;span style="color: green"&gt;// Did not recognize XmlNode as Shape element
    &lt;/span&gt;| _ &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;None &lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;pre class="code"&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;While the use of Active Patterns aren’t the easiest thing to read, they certainly allow you to easily convert data. &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;Part III – Computation Representation&lt;/h3&gt;
&lt;p&gt;This is the last part of Language Oriented Programming and definitely the most complicated. The theme of this essay has been that two languages are better than one; that using a domain-specific description the your problem makes the coding easier. The only thing better than two languages to represent your problem is not having to use three.&lt;/p&gt;
&lt;p&gt;Consider the common Forms-Over-Data application. You have a database, CustomerInfo, and you have your application written in C#. With any luck you’re using LOP in your programming and so you can represent your customer entities naturally, but you run into a problem as soon as you try to interface with your database. Namely, having your app talk to the database requires you using another language – SQL. &lt;/p&gt;
&lt;p&gt;With Visual Studio 2008 this problem was solved for a few specific scenarios with &lt;a href="http://msdn.microsoft.com/en-us/netframework/aa904594.aspx"&gt;Linq&lt;/a&gt;, but in F# you can solve this problem even more generally.&lt;/p&gt;
&lt;p&gt;This final aspect of LOP I’ll talk about is where you write F# code and manipulate the &lt;em&gt;computation which that code represents&lt;/em&gt;. In other words, you write some F# code that does something interesting and then manipulate the computation representation of that code to either execute that code in a unique way or convert that code into a different language.&lt;/p&gt;
&lt;p&gt;The F# language features Quotations and Workflows will undoubtedly be the subject of numerous articles, blog posts, and maybe even books in the future. So if I do a terrible job explaining what these features do, don’t fret.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Quotations&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Writing .NET code is great and all, but the implicit restriction is that your code is executing on computer running the .NET framework. That doesn’t sound like a big requirement, but think for a moment on how limiting that is. If you wanted to write code that executed on your GPU you would have to resort to &lt;a href="http://en.wikipedia.org/wiki/Cg_(programming_language)"&gt;some other language&lt;/a&gt;. Or let’s say you were multiplying two sparce matricies and wanted to optimize out all the zero-multiplications, leading to a more efficent code. You can’t. Because all the code you write in .NET must execute on the .NET platform… or at least it had to before F# came along.&lt;/p&gt;
&lt;p&gt;In F# the Quotations feature allows you to get access to the compiler’s representation of a block of code, enabling you to process that code as you wish. For example, you could &lt;strong&gt;write a Quotation-to-GPU converter and write programs in F# which could execute on your graphics card&lt;/strong&gt;. Or, given a function that operates on a sequence of data, convert those operation into SQL code and automatically query the server. (A la DLinq.)&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;I won’t go into details about how the code all works, but I’ll point out the key concepts. First, the funky “&amp;lt;@@ … @@&amp;gt;” code starts a quotation. Anything inbetween the &amp;lt;@@ and @@&amp;gt; is what is ‘quoted’. So the result of &amp;lt;@@ x @@&amp;gt; is the compiler’s representation of x. Second, once you have some quoted data you will can use Active Patterns to convert the compiler’s representation into something more useful. In the simplest example, we will take the quotation of a constant value and use an Active Pattern to convert the compiler’s representation of that into the value itself.&lt;/p&gt;&lt;pre class="code"&gt;#light

&lt;span style="color: blue"&gt;open &lt;/span&gt;Microsoft.FSharp.Quotations
&lt;span style="color: blue"&gt;open &lt;/span&gt;Microsoft.FSharp.Quotations.Typed
&lt;span style="color: blue"&gt;open &lt;/span&gt;Microsoft.FSharp.Quotations.Raw

&lt;span style="color: green"&gt;// The compiler represents the code “1” as an Int32 literal.
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;quot1 = &amp;lt;@@ 1 @@&amp;gt;

&lt;span style="color: blue"&gt;let &lt;/span&gt;printQuotation x =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;x &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| Int32 v  &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"The quoted code is an int with value %d" &lt;/span&gt;v
    | String v &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"The quoted code is a string with value %s" &lt;/span&gt;v
    | _        &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"I don't know what x is..."

&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;You can then move onto bigger, more complicated expressions by matching more types of expressions using Active Patterns. Here we break down an entire function.&amp;nbsp; (The [&amp;lt;ReflectedDefinition&amp;gt;] attribute is required for the function to be used inside of a quotation.)&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Functions
&lt;/span&gt;[&amp;lt;ReflectedDefinition&amp;gt;]
&lt;span style="color: blue"&gt;let &lt;/span&gt;checkTemp temp =
    &lt;span style="color: blue"&gt;if   &lt;/span&gt;temp &amp;lt; 60 &lt;span style="color: blue"&gt;then &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"Too cold"
    &lt;/span&gt;&lt;span style="color: blue"&gt;elif &lt;/span&gt;temp &amp;gt; 80 &lt;span style="color: blue"&gt;then &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"Too hot"
    &lt;/span&gt;&lt;span style="color: blue"&gt;else                &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"Just right"

&lt;/span&gt;&lt;span style="color: blue"&gt;let rec &lt;/span&gt;printQuotation2 expr =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;expr &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| ResolvedTopDefnUse(_,body) 
        &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"The expr is a Top Definition Use..."
           &lt;/span&gt;printQuotation2 body

    | Lambda(_, body) 
        &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"The expr is a Lambda..."
           &lt;/span&gt;printQuotation2 body
           
    | Cond(_, body, nextCond)
        &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"The expr is a Conditional..."
           &lt;/span&gt;printQuotation2 nextCond
           
    | App(info, body) 
        &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"The expr is a function application..."
   
    &lt;/span&gt;| _ &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"I don't know what the expr is"

&lt;/span&gt;printQuotation2 &amp;lt;@@ checkTemp @@&amp;gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Here is an example from &lt;em&gt;&lt;/em&gt;&lt;a href="http://www.amazon.com/Expert-F-Experts-Voice-Net/dp/1590598504"&gt;Expert F# (Apress, 2007)&lt;/a&gt; which uses Quotations to compute the error range for floating point calculations. Given an inexact number such as p = 3.141 +/- 0.001, repeated operations on p will result in a compounded error. Such as p + p = 6.282 +/- 0.002. Given the quotation of a function, the code will walk the compiler’s interpretation of the code and calculate an error estimate.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Example from Expert F# by Don Syme, Adam Granicz, and Antonio Cisternino
// Pg. 251

&lt;/span&gt;&lt;span style="color: blue"&gt;open &lt;/span&gt;Microsoft.FSharp.Quotations
&lt;span style="color: blue"&gt;open &lt;/span&gt;Microsoft.FSharp.Quotations.Typed
&lt;span style="color: blue"&gt;open &lt;/span&gt;Microsoft.FSharp.Quotations.Raw

&lt;span style="color: blue"&gt;type &lt;/span&gt;Error = Err &lt;span style="color: blue"&gt;of &lt;/span&gt;float

&lt;span style="color: green"&gt;// Estimate the error for a given expression, t.
// env is a map of identifiers to their values. E.g., "pi" -&amp;gt; 3.14159
&lt;/span&gt;&lt;span style="color: blue"&gt;let rec &lt;/span&gt;errorEstimateAux t (env : Map&amp;lt;_,_&amp;gt;) =

    &lt;span style="color: blue"&gt;match &lt;/span&gt;t &lt;span style="color: blue"&gt;with
    &lt;/span&gt;&lt;span style="color: green"&gt;// If the quoted expression matches the function application of
    // +, -, *, or / calculate the left and right hand sides and
    // compute the resulting error.
    &lt;/span&gt;| GenericTopDefnApp &amp;lt;@@ (+) @@&amp;gt; (tyargs,[xt;yt]) &lt;span style="color: blue"&gt;-&amp;gt;
        let &lt;/span&gt;x, Err(xerr) = errorEstimateAux xt env
        &lt;span style="color: blue"&gt;let &lt;/span&gt;y, Err(yerr) = errorEstimateAux yt env
        (x + y, Err(xerr + yerr))

    | GenericTopDefnApp &amp;lt;@@ (-) @@&amp;gt; (tyargs,[xt;yt]) &lt;span style="color: blue"&gt;-&amp;gt;
        let &lt;/span&gt;x, Err(xerr) = errorEstimateAux xt env
        &lt;span style="color: blue"&gt;let &lt;/span&gt;y, Err(yerr) = errorEstimateAux yt env
        (x - y, Err(xerr + yerr))

    | GenericTopDefnApp &amp;lt;@@ ( * ) @@&amp;gt; (tyargs,[xt;yt]) &lt;span style="color: blue"&gt;-&amp;gt;
        let &lt;/span&gt;x, Err(xerr) = errorEstimateAux xt env
        &lt;span style="color: blue"&gt;let &lt;/span&gt;y, Err(yerr) = errorEstimateAux yt env
        (x * y, Err(xerr * abs(x) + yerr * abs(y) + xerr * yerr))

    | GenericTopDefnApp &amp;lt;@@ ( / ) @@&amp;gt; (tyargs,[xt;yt]) &lt;span style="color: blue"&gt;-&amp;gt;
        let &lt;/span&gt;x, Err(xerr) = errorEstimateAux xt env
        &lt;span style="color: blue"&gt;let &lt;/span&gt;y, Err(yerr) = errorEstimateAux yt env
        (x / y, Err(xerr * abs(x) + abs(1.0 / y) / yerr + xerr / yerr))

    | GenericTopDefnApp &amp;lt;@@ abs @@&amp;gt; (tyargs,[xt]) &lt;span style="color: blue"&gt;-&amp;gt;
        let &lt;/span&gt;x,Err(xerr) = errorEstimateAux xt env
        (abs(x), Err(xerr))

    &lt;span style="color: green"&gt;// If the quoted expression introduced a new value. E.g.,
    // let e = 2.71828
    &lt;/span&gt;| Let((var,vet), bodyt) &lt;span style="color: blue"&gt;-&amp;gt;
        let &lt;/span&gt;varv, verr = errorEstimateAux vet env
        errorEstimateAux bodyt (env.Add(var.Name, (varv, verr)))

    | App(ResolvedTopDefnUse(info,Lambda(v,body)),arg) &lt;span style="color: blue"&gt;-&amp;gt;
        &lt;/span&gt;errorEstimateAux  (MkLet((v,arg),body)) env

    | Var(x) &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;env.[x]
    | Double(n) &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;(n,Err(0.0))

    | _ &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;failwithf &lt;span style="color: #a31515"&gt;"unrecognized term: %A" &lt;/span&gt;t

&lt;span style="color: blue"&gt;let rec &lt;/span&gt;errorEstimateRaw (t : Expr) =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;t &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| Lambda(x,t) &lt;span style="color: blue"&gt;-&amp;gt;
        &lt;/span&gt;(&lt;span style="color: blue"&gt;fun &lt;/span&gt;xv &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;errorEstimateAux t (Map.of_seq [(x.Name,xv)]))
    | ResolvedTopDefnUse(info,body) &lt;span style="color: blue"&gt;-&amp;gt;
        &lt;/span&gt;errorEstimateRaw body
    | _ &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;failwithf &lt;span style="color: #a31515"&gt;"unrecognized term: %A - expected a lambda" &lt;/span&gt;t

&lt;span style="color: blue"&gt;let rec &lt;/span&gt;errorEstimate (t : Expr&amp;lt;float &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;float&amp;gt;) = errorEstimateRaw t.Raw

&lt;span style="color: green"&gt;// ----------------------------

&lt;/span&gt;[&amp;lt;ReflectedDefinition&amp;gt;]
&lt;span style="color: blue"&gt;let &lt;/span&gt;poly x = x+2.0*x+3.0/(x*x)

errorEstimate &amp;lt;@ poly @&amp;gt; (3.0, Err(0.1))
&lt;span style="color: green"&gt;// Evaluates to: (9.333333333, Err 0.5821493625)

&lt;/span&gt;errorEstimate &amp;lt;@ poly @&amp;gt; (30271.3, Err(0.0001))
&lt;span style="color: green"&gt;// Evaluates to: (90813.9, Err 3.02723)&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;&lt;strong&gt;&lt;/strong&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Work flows&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Workflows are the most exciting language feature in F#, and represent perhaps the most powerful way to apply LOP in your code. But rather than telling you what they are I’ll build up to it.&lt;/p&gt;
&lt;p&gt;Consider this code, which is called a Sequence Expression. It produces a seq of the first 10 integers. The second example is a more complex sequence expression, which uses recursion to walk every file under a given directory. Note the use of recursion requires the ‘yield!’ keyword.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Sequence Expressions

// Numbers one through ten
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;numbers = seq { &lt;span style="color: blue"&gt;for &lt;/span&gt;i &lt;span style="color: blue"&gt;in &lt;/span&gt;1 .. 10 &lt;span style="color: blue"&gt;do
                        yield &lt;/span&gt;i }

&lt;span style="color: green"&gt;// All files under a given directory (notice the use of recursion)
&lt;/span&gt;&lt;span style="color: blue"&gt;open &lt;/span&gt;System.IO

&lt;span style="color: blue"&gt;let rec &lt;/span&gt;allFiles dir = 
    seq {   &lt;span style="color: blue"&gt;for &lt;/span&gt;file &lt;span style="color: blue"&gt;in &lt;/span&gt;Directory.GetFiles(dir) &lt;span style="color: blue"&gt;do
                yield &lt;/span&gt;file
            &lt;span style="color: blue"&gt;for &lt;/span&gt;subdir &lt;span style="color: blue"&gt;in &lt;/span&gt;Directory.GetDirectories dir &lt;span style="color: blue"&gt;do
                yield! &lt;/span&gt;(allFiles subdir) }
            
allFiles &lt;span style="color: #a31515"&gt;@"C:\Windows\System32\"&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Just to show that you can do powerful things with Sequence Expressions, here is some code to compute all prime numbers under 1,000. (The &lt;a href="http://blogs.msdn.com/chrsmith/archive/2008/04/29/sieve-of-eratosthenes-in-f.aspx"&gt;Sieve of Eratosthenes&lt;/a&gt; in F#.)&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Complex Sequence Expression
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;primesUnder1K = 
    seq { 
        &lt;span style="color: green"&gt;// First prime 
        &lt;/span&gt;&lt;span style="color: blue"&gt;yield &lt;/span&gt;2 

        &lt;span style="color: blue"&gt;let &lt;/span&gt;knownComposites = ref (Set.empty)
        
        &lt;span style="color: green"&gt;// Loop through all odd numbers; evens can't be prime 
        &lt;/span&gt;&lt;span style="color: blue"&gt;for &lt;/span&gt;i &lt;span style="color: blue"&gt;in &lt;/span&gt;3 .. 2 .. int 1000 &lt;span style="color: blue"&gt;do 
            
            &lt;/span&gt;&lt;span style="color: green"&gt;// Check if its in our list, if not, its prime 
            &lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;found = (!knownComposites).Contains(i) 
            &lt;span style="color: blue"&gt;if &lt;/span&gt;not found &lt;span style="color: blue"&gt;then 
                yield &lt;/span&gt;i 

            &lt;span style="color: green"&gt;// Add all multiples of i to our sieve, starting 
            // at i and irecementing by i. 
            &lt;/span&gt;&lt;span style="color: blue"&gt;do for &lt;/span&gt;j &lt;span style="color: blue"&gt;in &lt;/span&gt;i .. i .. int 1000 &lt;span style="color: blue"&gt;do 
                &lt;/span&gt;knownComposites := (!knownComposites).Add(j)
    } 

Seq.take 20 primesUnder1K&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;So to review, Sequence Expression produce seq objects and are use a seemingly limited subset of the F# language. Simple enough. &lt;/p&gt;
&lt;p&gt;Sequence Expressions however are just a specialization of a concept known as Computation Expression or Workflow. The Computation Expression was everything between the curly braces { and }. The ‘seq’ in front was the workflow &lt;em&gt;builder&lt;/em&gt; which I’ll come back to in a moment.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;So why are Computation Expressions important? Because in F# you can &lt;strong&gt;you define how the Computation Expression gets executed by using a builder object&lt;/strong&gt;. In the previous examples the ‘seq’ builder takes the Computation Expression and produces a sequence of values. But you can implement far more interesting builders. You could for example write a builder that logged every action that was taken, in order to better diagnose a failure in the code. Or even transfer the computation to a different machine and execute the code in the cloud. Computation Expressions / Workflows are a powerful new concept that open up a lot of possibilities for powerful language oriented concepts.&lt;/p&gt;
&lt;p&gt;The most practical application of workflows is in asynchronous programming. Normally if you want concurrent code you need to write it with a bunch of callbacks, manage thread states, deal with synclocks, and other unpleasantries. But using F# Asynchronous Workflows, all you need to do is write your code in a Computation Express and pass that computational representation of your code to the Async Workflow object. It will then execute that code doing all the async goo for you. &lt;strong&gt;That’s right, in F# you can write async code without even trying&lt;/strong&gt;. &lt;/p&gt;
&lt;p&gt;Here’s an example of an async workflow in F# from &lt;a href="http://www.amazon.com/Expert-F-Experts-Voice-Net/dp/1590598504"&gt;Expert F#&lt;/a&gt;. (Which for the record is a much better resource for teaching F# than my blog :)&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green"&gt;// Example from Expert F# by Don Syme, Adam Granicz, and Antonio Cisternino
// Pg. 366

&lt;/span&gt;&lt;span style="color: blue"&gt;open &lt;/span&gt;System.Net
&lt;span style="color: blue"&gt;open &lt;/span&gt;System.IO
&lt;span style="color: blue"&gt;open &lt;/span&gt;Microsoft.FSharp.Control.CommonExtensions

&lt;span style="color: blue"&gt;let &lt;/span&gt;museums = [&lt;span style="color: #a31515"&gt;"MOMA"&lt;/span&gt;,           &lt;span style="color: #a31515"&gt;"http://moma.org/"&lt;/span&gt;;
               &lt;span style="color: #a31515"&gt;"British Museum"&lt;/span&gt;, &lt;span style="color: #a31515"&gt;"http://www.thebritishmuseum.ac.uk/"&lt;/span&gt;;
               &lt;span style="color: #a31515"&gt;"Prado"&lt;/span&gt;,          &lt;span style="color: #a31515"&gt;"http://museoprado.mcu.es"&lt;/span&gt;;
               &lt;span style="color: #a31515"&gt;"SAM"&lt;/span&gt;,            &lt;span style="color: #a31515"&gt;"http://www.seattleartmuseum.org/"&lt;/span&gt;]

&lt;span style="color: green"&gt;// Fetch the museum website and print info to the console asynchronously
&lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;fetchAsync (name, url:string) =
    async { &lt;span style="color: blue"&gt;do &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"Creating request for %s..." &lt;/span&gt;name
            &lt;span style="color: blue"&gt;let &lt;/span&gt;req  = WebRequest.Create(url)

            &lt;span style="color: blue"&gt;let! &lt;/span&gt;resp  = req.GetResponseAsync()

            &lt;span style="color: blue"&gt;do &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"Getting response stream for %s..." &lt;/span&gt;name
            &lt;span style="color: blue"&gt;let &lt;/span&gt;stream = resp.GetResponseStream()

            &lt;span style="color: blue"&gt;do &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"Reading response for %s..." &lt;/span&gt;name
            &lt;span style="color: blue"&gt;let &lt;/span&gt;reader = &lt;span style="color: blue"&gt;new &lt;/span&gt;StreamReader(stream)
            &lt;span style="color: blue"&gt;let! &lt;/span&gt;html = reader.ReadToEndAsync()

            &lt;span style="color: blue"&gt;do &lt;/span&gt;printfn &lt;span style="color: #a31515"&gt;"Read %d characters for %s..." &lt;/span&gt;html.Length name }

&lt;span style="color: blue"&gt;for &lt;/span&gt;(name, url) &lt;span style="color: blue"&gt;in &lt;/span&gt;museums &lt;span style="color: blue"&gt;do
    &lt;/span&gt;Async.Spawn (fetchAsync(name,url))&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;That’s it. Seriously. The code will loop through all the museums specified, and asynchronously download the HTML of their homepages. All the work you needed to was write it inside of a Computation Expression and pass it to an ‘async’ builder. Async.Spawn will take the result and execute it asynchronously.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;/strong&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;I’ve shown that language features in F# enable Language Oriented Programming and provide all the power you need write succinct code that maps directly to your problem domain. No unnecessary code required. I fully expect that Language Oriented Programming becomes the driving force for F# adoption as developers discover the true expressiveness of the language and leverage these facilities. &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;*Actually, in a poor attempt at humor you’ve been &lt;a href="http://en.wikipedia.org/wiki/Rickroll"&gt;Rick Rolled&lt;/a&gt;. &lt;/p&gt;&lt;pre&gt;&lt;/pre&gt;&lt;pre&gt;&lt;/pre&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8564036" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/ChrisSmithsCompletelyUniqueView/~4/301450466" height="1" width="1"/&gt;</description><category domain="http://blogs.msdn.com/chrsmith/archive/tags/F_2300_/default.aspx">F#</category><category domain="http://blogs.msdn.com/chrsmith/archive/tags/Language+Oriented+Programming/default.aspx">Language Oriented Programming</category><feedburner:origLink>http://blogs.msdn.com/chrsmith/archive/2008/05/30/language-oriented-programming-in-f.aspx</feedburner:origLink></item><item><title>F# in 20 Minutes – Part II</title><link>http://feeds.feedburner.com/~r/ChrisSmithsCompletelyUniqueView/~3/287237532/f-in-20-minutes-part-ii.aspx</link><pubDate>Fri, 09 May 2008 22:19:39 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8482366</guid><dc:creator>ChrSmith</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/chrsmith/comments/8482366.aspx</comments><wfw:commentRss>http://blogs.msdn.com/chrsmith/commentrss.aspx?PostID=8482366</wfw:commentRss><description>&lt;p&gt;Now that we have covered the basics, in minutes 8 - 14 we will cover the foundational concepts and types in F#. By the end of Part II you should be able to read F# code reasonably well. &lt;/p&gt; &lt;h3&gt;Immutability&lt;/h3&gt; &lt;p&gt;You may have noticed that I’ve been using the term ‘value’ to refer to identifiers rather than ‘variable’. The reason for this is that types in F# are immutable by default, meaning that once they are created they cannot be changed. This may seem like a severe limitation, but immutability actually prevents &lt;a href="http://blogs.gotdotnet.com/jomo_fisher/archive/2007/05/16/leaky-functions-barrel-of-bugs.aspx"&gt;some classes of bugs&lt;/a&gt;. In addition, immutable data is inherently thread safe meaning you don’t need to worry about sync locks in order to make your code parallelizeable. I’ll go into asynchronous programming in Part III.&lt;/p&gt; &lt;p&gt;If you do need to mutate some data however, F# has the mutable keyword. This creates a variable who’s value can be changed by using the left arrow operator (&amp;lt;-).&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: black"&gt;&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;let mutable x = "the original value.";;
&lt;/span&gt;&lt;span style="color: black"&gt;val mutable x : string
&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;printfn "x's value is '%s'" x;;
&lt;/span&gt;&lt;span style="color: black"&gt;x's value is 'the original value.'
val it : unit = ()
&lt;/span&gt;&lt;/pre&gt;&lt;pre class="code"&gt;&lt;span style="color: black"&gt;&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;x &amp;lt;- "the new one.";;
&lt;/span&gt;&lt;span style="color: black"&gt;val it : unit = ()
&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;printfn "x's value is now '%s'" x;;
&lt;/span&gt;&lt;span style="color: black"&gt;x's value is now 'the new one.'
val it : unit = ()&lt;/span&gt;&lt;/pre&gt;&lt;pre class="code"&gt;&lt;span style="color: black"&gt;&lt;/span&gt;&amp;nbsp;&lt;/pre&gt;
&lt;h3&gt;Reference values (Microsoft.FSharp.Core.Ref&amp;lt;_&amp;gt;)&lt;/h3&gt;
&lt;p&gt;Reference values are another way of being able to mutate data. But rather than having a mutable variable on the stack, a reference cell is a pointer to variable which you modify on the heap. In F# there are some restrictions on where you can use mutable values. (Such as not being able to use them in inner lambdas.) But ref objects can be safely passed around, since they are immutable record values. (Which have a mutable field which can be modified.)&lt;/p&gt;
&lt;p&gt;To use reference cells you use (:=) to assign a new value and (!) to dereference.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: black"&gt;&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;let refCell = ref 42;;
&lt;/span&gt;&lt;span style="color: black"&gt;val refCell : int ref

&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;refCell := -1;;
&lt;/span&gt;&lt;span style="color: black"&gt;val it : unit = ()
&lt;/span&gt;&lt;/pre&gt;&lt;pre class="code"&gt;&lt;span style="color: black"&gt;&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;!refCell;;
&lt;/span&gt;&lt;span style="color: black"&gt;val it : int = –1&lt;/span&gt;&lt;/pre&gt;&lt;pre class="code"&gt;&lt;span style="color: black"&gt;&lt;/span&gt;&amp;nbsp;&lt;/pre&gt;
&lt;h3&gt;Modules&lt;/h3&gt;
&lt;p&gt;In Part I we just declared values and functions arbitrarily. You might have wondered ‘where did they go’, since in C# everything must belong to a class. Though F# can declare the standard .NET classes you are familiar with, it also has the notion of a module; which is a collection of values, functions, and types. (Contrast this with a namespace, which can only contain types.)&lt;/p&gt;
&lt;p&gt;This is how we were able to access ‘List.map’. In the F# library (FSharp.Core.dll) there is a module named ‘List’ and on that is a function named ‘map’. &lt;/p&gt;
&lt;p&gt;Modules serve as a way of encapsulating code when you are rapid prototyping without needing to spend the time to design a strict object-oriented type hierarchy.&amp;nbsp; To declare your own module, you can use the module keyword. In the example we will associate a mutable variable with the module, which will serve as a global variable. &lt;br&gt;&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;module &lt;/span&gt;ProgramSettings =
    &lt;span style="color: blue"&gt;let &lt;/span&gt;version = &lt;span style="color: maroon"&gt;"1.0.0.0"
    &lt;/span&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;debugMode = ref &lt;span style="color: blue"&gt;false
    
module &lt;/span&gt;MyProgram =
    
    &lt;span style="color: blue"&gt;do &lt;/span&gt;printfn &lt;span style="color: maroon"&gt;"Version %s" &lt;/span&gt;ProgramSettings.version
    
    &lt;span style="color: green"&gt;// You can also open modules like you can a namespace, which
    // brings all their functions and values into scope.
    &lt;/span&gt;&lt;span style="color: blue"&gt;open &lt;/span&gt;ProgramSettings
    debugMode := &lt;span style="color: blue"&gt;true&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;pre class="code"&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;Tuples &lt;/h3&gt;
&lt;p&gt;A tuple (pronounced 'two-pull') is an ordered collection of values treated like an atomic unit. Traditionally if you wanted to pass around a group of semi-related values you would need to create a struct or class, or perhaps rely on ‘out’ parameters. A tuple allows you to keep things organized by grouping related values together without introducing a new type.&lt;/p&gt;
&lt;p&gt;To define a tuple, simply enclose the group of values in parentheses separate the individual components by commas.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: black"&gt;&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;let tuple = (1, false, "text");;
&lt;/span&gt;&lt;span style="color: black"&gt;val tuple : int * bool * string

&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;let getNumberInfo (x : int) = (x, x.ToString(), x * x);;
&lt;/span&gt;&lt;span style="color: black"&gt;val getNumberInfo : int -&amp;gt; int * string * int

&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;getNumberInfo 42;;
&lt;/span&gt;&lt;span style="color: black"&gt;val it : int * string * int = (42, "42", 1764)&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Functions can even take tuples as arguments. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: black"&gt;&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;let printBlogInfo (owner, title, url) = printfn "%s's blog [%s] is online at '%s'" owner title url;; &lt;br&gt;&lt;/span&gt;&lt;span style="color: black"&gt;val printBlogInfo : string * string * string -&amp;gt; unit &lt;/span&gt;&lt;/pre&gt;&lt;pre class="code"&gt;&lt;span style="color: black"&gt;&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;let myBlog = ("Chris", "Completely Unique View", "http://blogs.msdn.com/chrsmith");;
&lt;/span&gt;&lt;span style="color: black"&gt;val myBlog : string * string * string
&lt;/span&gt;&lt;span style="color: black"&gt;
&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;printBlogInfo myBlog;;
&lt;/span&gt;&lt;span style="color: black"&gt;Chris's blog [Completely Unique View] is online at 'http://blogs.msdn.com/chrsmith'
val it : unit = ()
&lt;/span&gt;&amp;nbsp;&lt;/pre&gt;
&lt;h3&gt;Function Currying &lt;/h3&gt;
&lt;p&gt;A novel feature F# provides is the ability to provide a subset of a function’s parameters, and bind a new value to the partial application. This is known as function currying. For example, consider a function which takes three integers and returns their sum. We can curry that function, by fixing the first parameter to be 10, resulting in a function that only takes two integers and returns their sum plus 10.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: black"&gt;&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;let addThree x y z = x + y + z;;
&lt;/span&gt;&lt;span style="color: black"&gt;val addThree : int -&amp;gt; int -&amp;gt; int -&amp;gt; int

&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;let addTwo x y = addThree 10 x y;;
&lt;/span&gt;&lt;span style="color: black"&gt;val addTwo : int -&amp;gt; int -&amp;gt; int

&amp;gt; &lt;/span&gt;&lt;span style="color: #00008b"&gt;addTwo 1 1;;
&lt;/span&gt;&lt;span style="color: black"&gt;val it : int = 12
&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;Discriminated Unions&lt;/h3&gt;
&lt;p&gt;Consider the following enumeration:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;enum &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CardSuit &lt;/span&gt;{ Spade = 1, Club = 2, Heart = 3, Diamond = 4};&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Logically there can only be one possible suit for a card, but since an enum is just an integer behind the scenes you don’t actually know if the value is valid or not. For example, in C# you can write:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;CardSuit &lt;/span&gt;invalid1 = (&lt;span style="color: #2b91af"&gt;CardSuit&lt;/span&gt;) 9000;
&lt;span style="color: #2b91af"&gt;CardSuit &lt;/span&gt;invalid2 = &lt;span style="color: #2b91af"&gt;CardSuit&lt;/span&gt;.Club | &lt;span style="color: #2b91af"&gt;CardSuit&lt;/span&gt;.Diamond;&lt;/pre&gt;
&lt;p&gt;This will break any code that expects the enum to only have one of the four card values. Also, Consider the case where you need to extend an enum. (&lt;a href="http://blogs.msdn.com/jomo_fisher/archive/2008/04/22/correct-by-construction-in-f.aspx"&gt;Example borrowed from Jomo’s blog&lt;/a&gt;.)&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;enum &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Title &lt;/span&gt;{ Mr, Mrs }&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;The Title enum works great, but imagine that later you add a ‘Ms’ value. Now every single switch statement you had is a potential bug. You can try to fix up all your code, but you are bound to miss something. &lt;/p&gt;
&lt;p&gt;Enums provide a way to easily express some concepts but don’t provide enough compiler checks to prevent errors. Enter the Discriminated Union. A Discriminated Union in F# is a type which can only have one of a set of values, known as data tags. For example, consider a discriminated union for all Microsoft employees.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;MicrosoftEmployee =
    | BillGates
    | SteveBalmer
    | Worker &lt;span style="color: blue"&gt;of &lt;/span&gt;string
    | Lead   &lt;span style="color: blue"&gt;of &lt;/span&gt;string * MicrosoftEmployee list&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;&lt;/span&gt;&lt;br&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;If you have an instance of type MicrosoftEmployee, you know that it can only be one of {BillGates, SteveBalmer, Worker, or Lead}. Moreover, if it is a Worker then you know that there is an string associated with that data tag, probably corresponding to a name. We can create discriminated unions easily and use pattern matching - described later - to match their values.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;myBoss = Lead(&lt;span style="color: maroon"&gt;"Yasir"&lt;/span&gt;, [Worker(&lt;span style="color: maroon"&gt;"Chris"&lt;/span&gt;); Worker(&lt;span style="color: maroon"&gt;"Matteo"&lt;/span&gt;); Worker(&lt;span style="color: maroon"&gt;"Santosh"&lt;/span&gt;)])

&lt;span style="color: blue"&gt;let &lt;/span&gt;printGreeting (emp : MicrosoftEmployee) =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;emp &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| BillGates   &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: maroon"&gt;"Hello, Bill"
    &lt;/span&gt;| SteveBalmer &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: maroon"&gt;"Hello, Steve"
    &lt;/span&gt;| Worker(name) | Lead(name, _) 
                  &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: maroon"&gt;"Hello, %s" &lt;/span&gt;name&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Now what if we extend that Discriminated Union…&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;MicrosoftEmployee =
    | BillGates
    | SteveBalmer
    | Worker &lt;span style="color: blue"&gt;of &lt;/span&gt;string
    | Lead   &lt;span style="color: blue"&gt;of &lt;/span&gt;string * MicrosoftEmployee list
&lt;strong&gt;    | ChrisSmith&lt;/strong&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;… now we get a compiler warning in our match.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/chrsmith/WindowsLiveWriter/Fin20MinutesPartII_8E94/image_2.png"&gt;&lt;img title="image" style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="107" alt="image" src="http://blogs.msdn.com/blogfiles/chrsmith/WindowsLiveWriter/Fin20MinutesPartII_8E94/image_thumb.png" width="640" border="0"&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;The compiler detected that you didn’t match every tag of the discriminated union and issued a warning.&amp;nbsp; Checks like this go a long way towards preventing bugs.&amp;nbsp; To see a few examples of just how powerful discriminated unions are, check out &lt;a href="http://blogs.msdn.com/chrsmith/archive/2008/04/18/a-java-to-x86-compiler-written-in-f.aspx"&gt;this post&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;Pattern Matching&lt;/h3&gt;
&lt;p&gt;Pattern matching is like a powerful switch statement, allowing you to branch control flow. You can do more than just comparing a value against a constant however, pattern matching allows you to also capture new values. Such as in our previous example, we bound the identifier ‘name’ when matching against discriminated union tags.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;printGreeting (emp : MicrosoftEmployee) =
    &lt;span style="color: blue"&gt;match &lt;/span&gt;emp &lt;span style="color: blue"&gt;with
    &lt;/span&gt;| BillGates   &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: maroon"&gt;"Hello, Bill"
    &lt;/span&gt;| SteveBalmer &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;printfn &lt;span style="color: maroon"&gt;"Hello, Steve"
    &lt;/span