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

<channel>
	<title>Mindscape Blog &#187; F#</title>
	<atom:link href="http://www.mindscapehq.com/blog/index.php/category/f/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mindscapehq.com/blog</link>
	<description>The official blog of Mindscape</description>
	<lastBuildDate>Fri, 14 Jun 2013 05:34:30 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5</generator>
		<item>
		<title>Using WPF Elements from F#</title>
		<link>http://www.mindscapehq.com/blog/index.php/2012/04/29/using-wpf-elements-from-f/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2012/04/29/using-wpf-elements-from-f/#comments</comments>
		<pubDate>Mon, 30 Apr 2012 03:07:16 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[WPF Elements]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=4982</guid>
		<description><![CDATA[WPF and F#? It&#8217;s not a natural mix &#8212; Visual Studio doesn&#8217;t provide templates or tooling for F# WPF projects, and WPF&#8217;s implicit architecture normally implies mutable view models which are at odds with F#&#8217;s preference for immutable data types. But sometimes a project comes along which seems like a great fit for F#, and [...]]]></description>
				<content:encoded><![CDATA[<p>WPF and F#?  It&#8217;s not a natural mix &#8212; Visual Studio doesn&#8217;t provide templates or tooling for F# WPF projects, and WPF&#8217;s implicit architecture normally implies mutable view models which are at odds with F#&#8217;s preference for immutable data types.  But sometimes a project comes along which seems like a great fit for F#, <em>and</em> for a WPF front end.  A great example is data visualisation.  Retrieving and processing the data is exactly what F# does well, and innovative ways of presenting data are much easier to implement on WPF than on any other platform; and in a visualisation scenario the main view model is typically immutable.</p>
<p>I&#8217;m going to look at two ways of combining F# and WPF.  I&#8217;ll be using the Chart control from WPF Elements as my main example, but a lot of what I talk about here is equally applicable to any other WPF control, built-in or third-party.</p>
<p><strong>Solution 1: Hybrid C# and F# Solution</strong></p>
<p>The traditional way of using F# in a WPF application is to put the F# code into a class library, then invoke that class library from a C# or Visual Basic WPF application.  This works very easily &#8212; a C# application can call a F# class library just as easily as it can a C# class library, with full intellisense and debugging and everything else you&#8217;d expect.</p>
<p>For this example, I&#8217;m going to keep the F# class library very simple.  In reality, you probably wouldn&#8217;t create a separate class library for something this basic.  F# really starts to shine when you&#8217;re doing a bit more processing on your data, but to keep things simple I&#8217;m not going to do much more than download it.</p>
<p>The data I&#8217;m going to use is the <a href="https://datamarket.azure.com/dataset/b6092d85-5dc4-49a8-90a0-5f65e7ee2eec">London Borough Profiles</a> from the Windows Azure Datamarket.  This is dead easy to use in F# 3.0 thanks to the OData type provider:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">open Microsoft<span style="color: #008000;">.</span><span style="color: #0000FF;">FSharp</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Data</span><span style="color: #008000;">.</span><span style="color: #0000FF;">TypeProviders</span>
&nbsp;
type Boroughs <span style="color: #008000;">=</span> ODataService<span style="color: #008000;">&lt;</span><span style="color: #666666;">&quot;https://api.datamarket.azure.com/GreaterLondonAuthority/LondonBoroughProfiles/&quot;</span><span style="color: #008000;">&gt;</span>
&nbsp;
let dataContext <span style="color: #008000;">=</span> Boroughs<span style="color: #008000;">.</span><span style="color: #0000FF;">GetDataContext</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
dataContext<span style="color: #008000;">.</span><span style="color: #0000FF;">Credentials</span> <span style="color: #008000;">&lt;-</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Net</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">NetworkCredential</span><span style="color: #008000;">&#40;</span>YourUserName, YourAccountKey<span style="color: #008000;">&#41;</span></pre></div></div>

<p>For my view model, I want to extract just a subset of this data, so I define a couple of F# types to surface it:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">open <span style="color: #000000;">System.<span style="color: #0000FF;">Collections</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">Generic</span>
&nbsp;
type BoroughInfo <span style="color: #008000;">=</span> <span style="color: #008000;">&#123;</span>
  Area <span style="color: #008000;">:</span> <span style="color: #6666cc; font-weight: bold;">string</span>
  MaleLifeExpectancy <span style="color: #008000;">:</span> <span style="color: #6666cc; font-weight: bold;">float</span>
  FemaleLifeExpectancy <span style="color: #008000;">:</span> <span style="color: #6666cc; font-weight: bold;">float</span>
  Employment <span style="color: #008000;">:</span> <span style="color: #6666cc; font-weight: bold;">float</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
type ViewModel <span style="color: #008000;">=</span> <span style="color: #008000;">&#123;</span>
  Boroughs <span style="color: #008000;">:</span> List<span style="color: #008000;">&lt;</span>BoroughInfo<span style="color: #008000;">&gt;</span>    <span style="color: #008080; font-style: italic;">// not BoroughInfo list -- see below</span>
  National <span style="color: #008000;">:</span> BoroughInfo
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>These are F# immutable record types.  We don&#8217;t need to modify the data, so immutable types are easier to write and we don&#8217;t need to muck around with all that tedious INotifyPropertyChanged stuff.  The view model is going to include a list of entries for individual boroughs, plus a &#8216;dummy&#8217; borough representing national averages so I can display them alongside the per-borough data.</p>
<p>One gotcha is that the WPF Elements charting DataSeries expects an IList as its ItemsSource.  The F# list type doesn&#8217;t implement IList, so we have to be sure to make ViewModel.Boroughs a BCL List instead of a F# list.</p>
<p>Now we can build our view model:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let <span style="color: #008000;">&#40;</span>national, boroughs<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span>
  dataContext<span style="color: #008000;">.</span><span style="color: #0000FF;">LondonBoroughProfiles</span>
  <span style="color: #008000;">|&gt;</span> Seq<span style="color: #008000;">.</span><span style="color: #0000FF;">filter</span> <span style="color: #008000;">&#40;</span>fun r <span style="color: #008000;">-&gt;</span> r<span style="color: #008000;">.</span><span style="color: #0000FF;">MaleLifeExpectancy20072009</span><span style="color: #008000;">.</span><span style="color: #0000FF;">HasValue</span> <span style="color: #008000;">&amp;&amp;</span> r<span style="color: #008000;">.</span><span style="color: #0000FF;">FemaleLifeExpectancy20072009</span><span style="color: #008000;">.</span><span style="color: #0000FF;">HasValue</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">|&gt;</span> Seq<span style="color: #008000;">.</span><span style="color: #0000FF;">map</span> <span style="color: #008000;">&#40;</span>fun r <span style="color: #008000;">-&gt;</span> <span style="color: #008000;">&#123;</span> Area <span style="color: #008000;">=</span> r<span style="color: #008000;">.</span><span style="color: #0000FF;">Area</span><span style="color: #008000;">;</span> MaleLifeExpectancy <span style="color: #008000;">=</span> r<span style="color: #008000;">.</span><span style="color: #0000FF;">MaleLifeExpectancy20072009</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span><span style="color: #008000;">;</span> FemaleLifeExpectancy <span style="color: #008000;">=</span> r<span style="color: #008000;">.</span><span style="color: #0000FF;">FemaleLifeExpectancy20072009</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span><span style="color: #008000;">;</span> Employment <span style="color: #008000;">=</span> r<span style="color: #008000;">.</span><span style="color: #0000FF;">EmploymentRate2009</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">|&gt;</span> Seq<span style="color: #008000;">.</span><span style="color: #0000FF;">toList</span>
  <span style="color: #008000;">|&gt;</span> List<span style="color: #008000;">.</span><span style="color: #0000FF;">partition</span> <span style="color: #008000;">&#40;</span>fun b <span style="color: #008000;">-&gt;</span> b<span style="color: #008000;">.</span><span style="color: #0000FF;">Area</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;National Comparator&quot;</span><span style="color: #008000;">&#41;</span>
&nbsp;
let viewModel <span style="color: #008000;">=</span> <span style="color: #008000;">&#123;</span> Boroughs <span style="color: #008000;">=</span> List<span style="color: #008000;">&lt;</span>_<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>boroughs<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> National <span style="color: #008000;">=</span> List<span style="color: #008000;">.</span><span style="color: #0000FF;">head</span> national <span style="color: #008000;">&#125;</span></pre></div></div>

<p>Most of this should be self-explanatory &#8212; we are downloading all the borough data from the data context provided by the OData type provider, filtering out a couple of containers that don&#8217;t have data, and mapping away the nullable values.  (We could have done some of this using F# query expressions, but it&#8217;s not worth it for this data set.)  The only thing that may be unfamiliar is List.partition, which splits a list into two lists, the first containing things that satisfy the predicate and the second containing things that don&#8217;t.  The assignment therefore puts the &#8216;National Comparator&#8217; pseudo-borough into the &#8216;national&#8217; list, and the real boroughs into the &#8216;boroughs&#8217; list.</p>
<p>The end result of all this is a value called &#8216;viewModel&#8217; of type ViewModel, and we can now consume this from a C# application:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// Code-behind for MainWindow.xaml -- or of course you could automatically</span>
<span style="color: #008080; font-style: italic;">// wire it up using Caliburn Micro.</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> MainWindow <span style="color: #008000;">:</span> Window
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> MainWindow<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    InitializeComponent<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    DataContext <span style="color: #008000;">=</span> Data<span style="color: #008000;">.</span><span style="color: #0000FF;">viewModel</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:Chart</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;12&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:LineSeries</span> <span style="color: #000066;">ItemsSource</span>=<span style="color: #ff0000;">&quot;{Binding Boroughs}&quot;</span> <span style="color: #000066;">XBinding</span>=<span style="color: #ff0000;">&quot;{Binding Area}&quot;</span> <span style="color: #000066;">YBinding</span>=<span style="color: #ff0000;">&quot;{Binding MaleLifeExpectancy}&quot;</span> <span style="color: #000066;">SeriesBrush</span>=<span style="color: #ff0000;">&quot;Navy&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:LineSeries</span> <span style="color: #000066;">ItemsSource</span>=<span style="color: #ff0000;">&quot;{Binding Boroughs}&quot;</span> <span style="color: #000066;">XBinding</span>=<span style="color: #ff0000;">&quot;{Binding Area}&quot;</span> <span style="color: #000066;">YBinding</span>=<span style="color: #ff0000;">&quot;{Binding FemaleLifeExpectancy}&quot;</span> <span style="color: #000066;">SeriesBrush</span>=<span style="color: #ff0000;">&quot;Red&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:LineSeries</span> <span style="color: #000066;">ItemsSource</span>=<span style="color: #ff0000;">&quot;{Binding Boroughs}&quot;</span> <span style="color: #000066;">XBinding</span>=<span style="color: #ff0000;">&quot;{Binding Area}&quot;</span> <span style="color: #000066;">YBinding</span>=<span style="color: #ff0000;">&quot;{Binding Employment}&quot;</span> <span style="color: #000066;">YAxisTitle</span>=<span style="color: #ff0000;">&quot;Employment (%)&quot;</span> <span style="color: #000066;">SeriesBrush</span>=<span style="color: #ff0000;">&quot;Green&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:Chart.XAxis<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:ChartAxis</span> <span style="color: #000066;">LabelRotation</span>=<span style="color: #ff0000;">&quot;90&quot;</span> <span style="color: #000066;">LabelStep</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000066;">MajorTickSpacing</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/e:Chart.XAxis<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:Chart.YAxis<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:ChartAxis</span> <span style="color: #000066;">Minimum</span>=<span style="color: #ff0000;">&quot;65&quot;</span> <span style="color: #000066;">Maximum</span>=<span style="color: #ff0000;">&quot;90&quot;</span> <span style="color: #000066;">Title</span>=<span style="color: #ff0000;">&quot;Life Expectancy (yr)&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/e:Chart.YAxis<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:Chart.AlternativeYAxes<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:ChartAxis</span> <span style="color: #000066;">Minimum</span>=<span style="color: #ff0000;">&quot;50&quot;</span> <span style="color: #000066;">Maximum</span>=<span style="color: #ff0000;">&quot;100&quot;</span> <span style="color: #000066;">Title</span>=<span style="color: #ff0000;">&quot;Employment (%)&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/e:Chart.AlternativeYAxes<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/e:Chart<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p><a href="http://www.mindscapehq.com/blog/wp-content/uploads/2012/04/chart.png"><img src="http://www.mindscapehq.com/blog/wp-content/uploads/2012/04/chart.png" alt="" title="Chart from C# application displaying data from F# class library" width="735" height="360" class="alignleft size-full wp-image-4983" /></a></p>
<p><strong>Solution 2: All F# Solution</strong></p>
<p>With F# 3.0, though, it&#8217;s now feasible to build WPF applications <em>entirely</em> in F#, without needing to put the user interface into C#.  In practice I know most readers of this blog will probably feel more at home in C# than in F# so they&#8217;ll want to use F# only for the core data processing anyway &#8212; but I think it&#8217;s interesting to know how F# 3.0 enables XAML support, plus there are a couple of things that may not be quite so obvious!  (This example is based on <a href="http://www.navision-blog.de/2012/03/22/wpf-designer-for-f/">Steffen Forkmann&#8217;s WPF Designer for F# announcement</a>, which is in turn based on <a href="http://sharp-gamedev.blogspot.de/">Johann Deneux&#8217;</a> XAML type provider.)</p>
<p>The first thing we need to do is create a Windows Application F# project.  There isn&#8217;t a template for this, but we can take our class library project, go into Properties > Application, and change the Output Type to Windows Application (and add a Program.fs file to contain the application code).  Or we can create a new F# Application project and change the Output Type from Console Application to Windows Application.</p>
<p>Next we need the XAML type provider.  This is available as a NuGet package from the FSharpx folks.  Right-click the F# project, choose Manage NuGet Packages, search for FSharpx.TypeProviders and click Install.  (<a href="https://github.com/fsharp/fsharpx">Learn more about FSharpx here.</a>)</p>
<p>We also need to add references to the WPF assemblies (WindowsBase, PresentationCore, PresentationFramework and System.Xaml) and to the WPF Elements DLL.</p>
<p>The last piece of plumbing we need is to handle the licensed controls in WPF Elements.  Copy the licenses.licx file from the WPF Elements Sample Explorer to the F# project directory, include it in the F# project and set its Build Action to Embedded Resource.</p>
<p>Now we&#8217;re ready to roll, where by &#8216;roll&#8217; I mean create an actual WPF window.</p>
<p>Right-click the project and choose Add New Item.  There&#8217;s no XAML template but just choose XML File and change the file extension to .xaml, e.g. MainWindow.xaml.  Replace the contents of the .xaml file with the following:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Window</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">xmlns:x</span>=<span style="color: #ff0000;">&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">xmlns:e</span>=<span style="color: #ff0000;">&quot;clr-namespace:Mindscape.WpfElements.Charting;assembly=Mindscape.WpfElements&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">Title</span>=<span style="color: #ff0000;">&quot;MainWindow&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;500&quot;</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;900&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:Chart<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:LineSeries</span> <span style="color: #000066;">ItemsSource</span>=<span style="color: #ff0000;">&quot;{Binding Boroughs}&quot;</span> <span style="color: #000066;">XBinding</span>=<span style="color: #ff0000;">&quot;{Binding Area}&quot;</span> <span style="color: #000066;">YBinding</span>=<span style="color: #ff0000;">&quot;{Binding MaleLifeExpectancy}&quot;</span> <span style="color: #000066;">SeriesBrush</span>=<span style="color: #ff0000;">&quot;Navy&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:LineSeries</span> <span style="color: #000066;">ItemsSource</span>=<span style="color: #ff0000;">&quot;{Binding Boroughs}&quot;</span> <span style="color: #000066;">XBinding</span>=<span style="color: #ff0000;">&quot;{Binding Area}&quot;</span> <span style="color: #000066;">YBinding</span>=<span style="color: #ff0000;">&quot;{Binding FemaleLifeExpectancy}&quot;</span> <span style="color: #000066;">SeriesBrush</span>=<span style="color: #ff0000;">&quot;Red&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:LineSeries</span> <span style="color: #000066;">ItemsSource</span>=<span style="color: #ff0000;">&quot;{Binding Boroughs}&quot;</span> <span style="color: #000066;">XBinding</span>=<span style="color: #ff0000;">&quot;{Binding Area}&quot;</span> <span style="color: #000066;">YBinding</span>=<span style="color: #ff0000;">&quot;{Binding Employment}&quot;</span> <span style="color: #000066;">YAxisTitle</span>=<span style="color: #ff0000;">&quot;Employment&quot;</span> <span style="color: #000066;">SeriesBrush</span>=<span style="color: #ff0000;">&quot;Green&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:Chart.XAxis<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:ChartAxis</span> <span style="color: #000066;">LabelRotation</span>=<span style="color: #ff0000;">&quot;90&quot;</span> <span style="color: #000066;">LabelStep</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000066;">MajorTickSpacing</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/e:Chart.XAxis<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:Chart.YAxis<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:ChartAxis</span> <span style="color: #000066;">Minimum</span>=<span style="color: #ff0000;">&quot;65&quot;</span> <span style="color: #000066;">Maximum</span>=<span style="color: #ff0000;">&quot;90&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/e:Chart.YAxis<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:Chart.AlternativeYAxes<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;e:ChartAxis</span> <span style="color: #000066;">Minimum</span>=<span style="color: #ff0000;">&quot;50&quot;</span> <span style="color: #000066;">Maximum</span>=<span style="color: #ff0000;">&quot;100&quot;</span> <span style="color: #000066;">Title</span>=<span style="color: #ff0000;">&quot;Employment&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/e:Chart.AlternativeYAxes<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/e:Chart<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Window<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>One little nasty to watch out for: the F# XAML type provider currently handles only &#8216;clr-namespace&#8217; namespaces.  So we have to refer to the Mindscape.WpfElements.Charting namespace by name, instead of using the URI.  Other than that this is the same XAML as in the C# application.</p>
<p>Finally we need to write some code to launch this window and associate it with our view model.  In C#, the project template handled this for us but in F# we need to do it ourselves.  Fortunately all the hard work is done by the XAML type provider:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">open <span style="color: #000000;">System</span>
open <span style="color: #000000;">System</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Windows</span>
open FSharpx
&nbsp;
type MainWindow <span style="color: #008000;">=</span> XAML<span style="color: #008000;">&lt;</span><span style="color: #666666;">&quot;MainWindow.xaml&quot;</span><span style="color: #008000;">&gt;</span>  <span style="color: #008080; font-style: italic;">// creates the MainWindow type from the MainWindow.xaml file</span>
&nbsp;
let loadWindow<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span>
  let window <span style="color: #008000;">=</span> MainWindow<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>  <span style="color: #008080; font-style: italic;">// creates a new instance of MainWindow</span>
  window<span style="color: #008000;">.</span><span style="color: #0000FF;">Root</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DataContext</span> <span style="color: #008000;">&lt;-</span> Data<span style="color: #008000;">.</span><span style="color: #0000FF;">viewModel</span>
  window<span style="color: #008000;">.</span><span style="color: #0000FF;">Root</span>
&nbsp;
<span style="color: #008000;">&#91;</span><span style="color: #008000;">&lt;</span>STAThread<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#93;</span>
<span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> Application<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Run</span><span style="color: #008000;">&#40;</span>loadWindow<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">|&gt;</span> ignore</pre></div></div>

<p>You can now build and run the application, and you&#8217;ll find it works just like the C# one.  Of course, it has taken a bit more effort to set up, but that&#8217;s a one-off, and you can now enjoy using F# for your interaction logic as well as your business logic.</p>
<p><a href='http://www.mindscapehq.com/blog/wp-content/uploads/2012/04/FSharpElements.zip'>You can download the source for the F# WPF Elements demo project here.</a>  You will need Visual Studio 11 Beta, and a copy of <a href="http://www.mindscapehq.com/products/wpfelements">Mindscape WPF Elements</a> (<a href="http://www.mindscapehq.com/products/wpfelements/download">download the free edition including a 60-day trial of the charting controls</a>).  (To run the program, you&#8217;ll also need to sign up for the free <a href="https://datamarket.azure.com/dataset/b6092d85-5dc4-49a8-90a0-5f65e7ee2eec">London Borough Profiles</a> data set on Azure Datamarket.)  If you have any questions or problems, post in the comments or the <a href="http://www.mindscapehq.com/forums/forum/15">support forum</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2012/04/29/using-wpf-elements-from-f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Codemania: How to not write a for loop</title>
		<link>http://www.mindscapehq.com/blog/index.php/2012/04/01/codemania-how-to-not-write-a-for-loop/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2012/04/01/codemania-how-to-not-write-a-for-loop/#comments</comments>
		<pubDate>Sun, 01 Apr 2012 23:42:42 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=4841</guid>
		<description><![CDATA[It was great to see so many Mindscape customers at Codemania. We were proud to sponsor the first Codemania and it looks like everyone is looking forward to another one next year! In the meantime, here are the slides and code samples from the &#8216;How to Not Write a For Loop&#8217; talk: Download slides (PowerPoint [...]]]></description>
				<content:encoded><![CDATA[<p>It was great to see so many Mindscape customers at <a href="http://www.codemania.co.nz/">Codemania</a>.  We were proud to sponsor the first Codemania and it looks like everyone is looking forward to another one next year!</p>
<p>In the meantime, here are the slides and code samples from the &#8216;How to Not Write a For Loop&#8217; talk:</p>
<ul>
<li><a href='http://www.mindscapehq.com/blog/wp-content/uploads/2012/04/HowToNotWriteAForLoop_Slides.pptx'>Download slides (PowerPoint 2010 format)</a></li>
<li><a href='http://www.mindscapehq.com/blog/wp-content/uploads/2012/04/HowToNotWriteAForLoop_CodeSamples.zip'>Download samples</a> (LIMITED EDITION DIRECTOR&#8217;S CUT featuring deleted samples and NEVER BEFORE SEEN out-takes)</li>
</ul>
<p>And don&#8217;t forget that if you attended Codemania then we&#8217;re offering you a free copy of <a href="http://www.mindscapehq.com/products/web-workbench">Web Workbench</a> <a href="http://www.mindscapehq.com/products/web-workbench/go-pro">Pro</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2012/04/01/codemania-how-to-not-write-a-for-loop/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>5 1/2 F# features every C# programmer should lust after</title>
		<link>http://www.mindscapehq.com/blog/index.php/2012/03/27/5-12-f-features-every-c-programmer-should-lust-after/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2012/03/27/5-12-f-features-every-c-programmer-should-lust-after/#comments</comments>
		<pubDate>Wed, 28 Mar 2012 01:36:23 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=4779</guid>
		<description><![CDATA[C# is a great programming language, but there&#8217;s still a bevy of features in other programming languages that I often wish were in C#. I&#8217;m doing quite a bit of work in F# nowadays, and I thought it would be fun to jot down a few F# features that I really miss when I come [...]]]></description>
				<content:encoded><![CDATA[<p>C# is a great programming language, but there&#8217;s still a bevy of features in other programming languages that I often wish were in C#.  I&#8217;m doing quite a bit of work in F# nowadays, and I thought it would be fun to jot down a few F# features that I really miss when I come back to C#.</p>
<p><strong>1. The Option type</strong></p>
<p>Tony Hoare, the inventor of the null reference, called it his &#8216;billion dollar mistake.&#8217;  Null is a disaster because it means that every reference type has a magic value that will destroy your program.  For value types, we now have &#8216;normal&#8217; value types and nullable value types to express the difference between, say, &#8216;this function returns an integer&#8217; and &#8216;this function might return an integer, or it might not.&#8217;  But we don&#8217;t have that for reference types.</p>
<p>F# provides the Option type to distinguish between &#8216;there definitely is a value&#8217; and &#8216;there might or might not be a value.&#8217;  F#&#8217;s Option is a bit like Nullable but can be used with any type, value or reference, and comes equipped with helper functions and pattern matching support.  Here&#8217;s an example of Option in use:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let names <span style="color: #008000;">=</span> <span style="color: #008000;">&#91;</span> <span style="color: #666666;">&quot;alice&quot;</span><span style="color: #008000;">;</span> <span style="color: #666666;">&quot;bob&quot;</span><span style="color: #008000;">;</span> <span style="color: #666666;">&quot;carol&quot;</span><span style="color: #008000;">&#93;</span>
let name <span style="color: #008000;">=</span> List<span style="color: #008000;">.</span><span style="color: #0000FF;">tryFind</span> <span style="color: #008000;">&#40;</span>fun s <span style="color: #008000;">-&gt;</span> length s <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">4</span><span style="color: #008000;">&#41;</span> names  <span style="color: #008080; font-style: italic;">// returns an Option</span>
match name with
<span style="color: #008000;">|</span> Some n <span style="color: #008000;">-&gt;</span> printfn <span style="color: #666666;">&quot;%s has a short name&quot;</span> n
<span style="color: #008000;">|</span> None   <span style="color: #008000;">-&gt;</span> printfn <span style="color: #666666;">&quot;They all have long names&quot;</span></pre></div></div>

<p>Notice that if we erroneously try to use the option returned from List.tryFind as if it were a real string, the error is caught at compile time:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let names <span style="color: #008000;">=</span> <span style="color: #008000;">&#91;</span> <span style="color: #666666;">&quot;alice&quot;</span><span style="color: #008000;">;</span> <span style="color: #666666;">&quot;bob&quot;</span><span style="color: #008000;">;</span> <span style="color: #666666;">&quot;carol&quot;</span><span style="color: #008000;">&#93;</span>
let name <span style="color: #008000;">=</span> List<span style="color: #008000;">.</span><span style="color: #0000FF;">tryFind</span> <span style="color: #008000;">&#40;</span>fun s <span style="color: #008000;">-&gt;</span> length s <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">4</span><span style="color: #008000;">&#41;</span> names  <span style="color: #008080; font-style: italic;">// returns an Option</span>
printfn <span style="color: #666666;">&quot;%s has a short name&quot;</span> name  <span style="color: #008080; font-style: italic;">// Error! Expected string but got string option</span></pre></div></div>

<p>In C#, the &#8216;not found&#8217; case would be represented by null, and the compiler would not be able to catch the potential error.</p>
<p>The <a href="https://github.com/fsharp/fsharpx">FSharpx project</a> provides some helpers to make it easy to use the F# Option type from C#, though it&#8217;s of limited use except in interop because the C# compiler still won&#8217;t stop you using nulls even in non-optional situations.</p>
<p><strong>2. Immutable record types</strong></p>
<p>Immutable types are a great way to improve the correctness of programs.  Any type that represents a value, rather than an entity which needs to preserve identity as its attributes change, should be immutable.  Even quite complex objects, such as expression trees in LINQ or syntax trees in Roslyn, benefit from immutability.  Unfortunately, C# makes it far more effort to write immutable types than mutable ones.  Here&#8217;s two ways to implement a 2D Point type in C#, one mutable (wrong!) and one immutable (right!):</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> MutablePoint <span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">double</span> X <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">double</span> Y <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> ImmutablePoint <span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> <span style="color: #6666cc; font-weight: bold;">double</span> _x<span style="color: #008000;">;</span>
  <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> <span style="color: #6666cc; font-weight: bold;">double</span> _x<span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">public</span> ImmutablePoint<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">double</span> x, <span style="color: #6666cc; font-weight: bold;">double</span> y<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    _x <span style="color: #008000;">=</span> x<span style="color: #008000;">;</span>
    _y <span style="color: #008000;">=</span> y<span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">double</span> X <span style="color: #008000;">&#123;</span> get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _x<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span> <span style="color: #008000;">&#125;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">double</span> Y <span style="color: #008000;">&#123;</span> get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _y<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The safe, immutable type is more than twice as long!</p>
<p>Contrast this with F#:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">type Point <span style="color: #008000;">=</span> <span style="color: #008000;">&#123;</span> X <span style="color: #008000;">:</span> <span style="color: #6666cc; font-weight: bold;">float</span><span style="color: #008000;">;</span> Y <span style="color: #008000;">:</span> <span style="color: #6666cc; font-weight: bold;">float</span> <span style="color: #008000;">&#125;</span></pre></div></div>

<p>It&#8217;s short, it&#8217;s immutable and as a special wonder bonus it&#8217;s got proper value equality built in for free.  And I want it in C#, pronto.</p>
<p><strong>3. Object expressions</strong></p>
<p>Object expressions are a great feature for when you want to implement an interface or override a class member without going to the trouble of spinning out an entire class or subclass for it.  This can dramatically reduce the amount of code particularly when you need to capture local variables for your implementation or override.  (If you&#8217;re familiar with Java&#8217;s local classes, object expressions are a lot like that.)  Here&#8217;s an example using the LightSpeed IAuditInfoStrategy interface:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// blame takes a string and returns an IAuditInfoStrategy</span>
let blame x <span style="color: #008000;">=</span> <span style="color: #008000;">&#123;</span>
  <span style="color: #008000;">new</span> IAuditInfoStrategy with
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Mode</span> <span style="color: #008000;">=</span> AuditInfoMode<span style="color: #008000;">.</span><span style="color: #0000FF;">Custom</span>
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrentUser</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> x <span style="color: #008000;">&#125;</span></pre></div></div>

<p>In C#, I would have had to write out a ScapegoatingAuditInfoStrategy class with a field to hold the blamee and a constructor to pass the blamee into the class.  In F#, I just told the compiler to make me an IAuditInfoStrategy that always blamed x, and it did.  I often end up writing lots of little classes to capture small nuggets of code or fragments of state, and it would be great if C# had something like object expressions to make it easier.</p>
<p><a href="http://www.mindscapehq.com/blog/index.php/2011/03/17/object-expressions-in-f/">More about object expressions here.</a></p>
<p><strong>4. Partial application</strong></p>
<p>I actually like C# lambda syntax more than F#.  This is just as well, because I have to write a lot more lambdas in C# than I do in F#.  The reason is that in F# I can use a trick called partial application to reuse a &#8216;normal&#8217; function just with particular arguments.  Let&#8217;s see an example.</p>
<p>Suppose I want to double every element in a sequence.  I can do that using the LINQ Select operator, or its F# equivalent Seq.map:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// C#</span>
var doubled <span style="color: #008000;">=</span> values<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Select</span><span style="color: #008000;">&#40;</span>v <span style="color: #008000;">=&gt;</span> v <span style="color: #008000;">*</span> <span style="color: #FF0000;">2</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// F#</span>
let doubled <span style="color: #008000;">=</span> Seq<span style="color: #008000;">.</span><span style="color: #0000FF;">map</span> <span style="color: #008000;">&#40;</span>fun v <span style="color: #008000;">-&gt;</span> v <span style="color: #008000;">*</span> <span style="color: #FF0000;">2</span><span style="color: #008000;">&#41;</span> values</pre></div></div>

<p>C# code is more concise than F# code, right?  Not so fast!  In F# we can partially apply the * function and save ourselves writing the lambda!</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let doubled <span style="color: #008000;">=</span> Seq<span style="color: #008000;">.</span><span style="color: #0000FF;">map</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">*</span><span style="color: #008000;">&#41;</span> <span style="color: #FF0000;">2</span><span style="color: #008000;">&#41;</span> values</pre></div></div>

<p>Of course you can do this with your own functions too:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let isDivisibleBy x y <span style="color: #008000;">=</span> y <span style="color: #008000;">%</span> x <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>
let evens <span style="color: #008000;">=</span> List<span style="color: #008000;">.</span><span style="color: #0000FF;">filter</span> <span style="color: #008000;">&#40;</span>isDivisibleBy <span style="color: #FF0000;">2</span><span style="color: #008000;">&#41;</span> values  <span style="color: #008080; font-style: italic;">// rather than (fun v -&gt; isDivisibleBy 2 v)</span></pre></div></div>

<p>Partial application reduces the amount of lambda noise in the code, and can also be useful in creating new functions by specialising existing ones.  <a href="http://hestia.typepad.com/flatlander/2011/06/partial-function-application-in-f-index.html">You can read more about partial application in this series</a> and (more concisely) in <a href="http://www.mindscapehq.com/blog/index.php/2010/10/13/f-and-first-class-functions-part-3-partial-function-application/">this article</a>.</p>
<p><strong>5. Pattern matching</strong></p>
<p><a href="http://hestia.typepad.com/flatlander/2010/07/f-pattern-matching-for-beginners-index.html">I&#8217;ve written extensively about pattern matching elsewhere</a>, and it&#8217;s too big a topic to explain thoroughly here.  Pattern matching allows you to combine programming by cases (like a switch statement) with custom logic (like an if statement) and decomposing composites to get the bits you&#8217;re interested in (like a series of property accesses or collection operations).  It&#8217;s also extensible using active patterns, which means you can build classifiers independently of the routines that use the classification.  And patterns compose far more conveniently than imperative code.</p>
<p>One often-overlooked but very powerful feature of pattern matching is that it can be used in a let statement.  This allows you to effectively return multiple values from a function without having to create a XxxResult type or explicitly picking apart a tuple.  Combined with the F# compiler being able to silently translate C# out-parameters into tupled return values, this creates some neat, readable idioms:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let dict <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
let <span style="color: #008000;">&#40;</span>found, result<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> dict<span style="color: #008000;">.</span><span style="color: #0000FF;">TryGetValue</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;alice&quot;</span><span style="color: #008000;">&#41;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// C# equivalent</span>
var dict <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">string</span> result <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">bool</span> found <span style="color: #008000;">=</span> dict<span style="color: #008000;">.</span><span style="color: #0000FF;">TryGetResult</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;alice&quot;</span>, <span style="color: #0600FF; font-weight: bold;">out</span> result<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>There&#8217;s much more to pattern matching than this, including <a href="http://hestia.typepad.com/flatlander/2010/07/f-pattern-matching-for-beginners-part-4-lists-and-recursion.html">recursing over lists</a>, visiting over class hierarchies (<a href="http://hestia.typepad.com/flatlander/2012/02/discriminated-unions-in-f.html">discriminated unions</a>), working safely with options, type-checking and casting, and, well, the list goes on.  I use pattern matching all the time in F# and I always miss it when I have to come back to C# and write imperative (if-style) code to distinguish between cases.</p>
<p><strong>5 1/2. Async</strong></p>
<p>F#&#8217;s async workflows make it easy to write asynchronous code in a readable, easy to understand, top-to-bottom way.  This is compelling &#8212; so compelling, in fact, that <a href="http://www.mindscapehq.com/blog/index.php/2012/03/13/asynchronous-programming-in-c-5/">a similar feature is going to be adopted into C#</a>.  F# still has a bunch of async features that haven&#8217;t made it into C#, notably async agents, but for the core scenario C# programmers no longer need to be envious!</p>
<p><strong>And there&#8217;s more</strong></p>
<p>There&#8217;s so much in F# that would be a huge boon for C# that I could easily have made this a top 10 list.  Some of F#&#8217;s features can be used from C# (read <a href="http://bugsquash.blogspot.co.nz/2011/10/10-reasons-to-use-f-runtime-in-your-c.html">Mauricio Scheffer&#8217;s great post on &#8217;10 reasons to use the F# runtime in your C# app&#8217;</a>) but a lot of the features I miss are part of the language.  For example, I&#8217;d love to see F#-level type inference in C#.  After all, which one of these declarations do you find easier to read?</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// C#</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> IEnumerable<span style="color: #008000;">&lt;</span>TResult<span style="color: #008000;">&gt;</span> Map<span style="color: #008000;">&lt;</span>TSource, TResult<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span> IEnumerable<span style="color: #008000;">&lt;</span>TSource<span style="color: #008000;">&gt;</span> source, Func<span style="color: #008000;">&lt;</span>TSource, TResult<span style="color: #008000;">&gt;</span> selector<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #008000;">...</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008080; font-style: italic;">// F#</span>
let map selector source <span style="color: #008000;">=</span> <span style="color: #008000;">...</span>  <span style="color: #008080; font-style: italic;">// F# infers types and generic type parameters from implementation</span></pre></div></div>

<p>Or how about <a href="http://www.mindscapehq.com/blog/index.php/2011/02/28/recursive-iterators-in-f/">recursive iterators</a>?  Or an interactive prompt in Visual Studio, so you could try out snippets or run demos without having to build a console or NUnit project?  (Roslyn has a C# Interactive window, but Roslyn&#8217;s still some way off!)  And looking to the future, <a href="http://www.mindscapehq.com/blog/index.php/2011/09/19/f-type-providers-as-if-by-magic/">F# type providers</a> open up a whole new order of expressiveness beyond standard code generation techniques.</p>
<p>So what&#8217;s in your top 5?  What F# features do you miss when you go back to C#?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2012/03/27/5-12-f-features-every-c-programmer-should-lust-after/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>F# type providers &#8211; as if by magic&#8230;</title>
		<link>http://www.mindscapehq.com/blog/index.php/2011/09/19/f-type-providers-as-if-by-magic/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2011/09/19/f-type-providers-as-if-by-magic/#comments</comments>
		<pubDate>Tue, 20 Sep 2011 00:45:29 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=3759</guid>
		<description><![CDATA[F# 3 will introduce a new feature called type providers. A type provider is a gadget that creates new types for you. The F# team, reflecting their focus on data access, have shipped type providers for databases, DBML and EDMX files, and WSDL and OData services. If you use one of these type providers in [...]]]></description>
				<content:encoded><![CDATA[<p>F# 3 will introduce a new feature called <em>type providers</em>.  A type provider is a gadget that creates new types for you.  The F# team, reflecting their focus on data access, have shipped type providers for databases, DBML and EDMX files, and WSDL and OData services.  If you use one of these type providers in your F# program, it will give you strong-typed access to the database or service.  So from this point of view it&#8217;s a lot like the code generator that runs when you create a DBML or EDMX file, or do an Add Service Reference to a Web service or OData service.</p>
<p>But F# type providers can create any kind of type, and they don&#8217;t need to consult an external resource to do it.  This means a type provider can be used to automagically replace repetitive boilerplate code with a simple declaration.</p>
<p>Consider a vector maths library.  Users will want to be able to create vectors with various numbers of dimensions &#8212; 2D vectors, 3D vectors, etc.  And they might even want to be able to create vectors with the same number of dimensions but different names (for example, Horizontal/Vertical instead of X/Y).  In C#, you&#8217;d have to write out each vector type by hand.  In F# 3, you can ship a Vector type provider, and users can create their desired vector types from that:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">type Vector2D <span style="color: #008000;">=</span> Vector<span style="color: #008000;">&lt;</span><span style="color: #666666;">&quot;X&quot;</span>, <span style="color: #666666;">&quot;Y&quot;</span><span style="color: #008000;">&gt;</span>
type Vector3D <span style="color: #008000;">=</span> Vector<span style="color: #008000;">&lt;</span><span style="color: #666666;">&quot;X&quot;</span>, <span style="color: #666666;">&quot;Y&quot;</span>, <span style="color: #666666;">&quot;Z&quot;</span><span style="color: #008000;">&gt;</span>
type VectorHV <span style="color: #008000;">=</span> Vector<span style="color: #008000;">&lt;</span><span style="color: #666666;">&quot;Horizontal&quot;</span>, <span style="color: #666666;">&quot;Vertical&quot;</span><span style="color: #008000;">&gt;</span>
&nbsp;
let v1 <span style="color: #008000;">=</span> Vector2D<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
v1<span style="color: #008000;">.</span><span style="color: #0000FF;">X</span> <span style="color: #008000;">&lt;-</span> <span style="color: #FF0000;">100.0</span>
v1<span style="color: #008000;">.</span><span style="color: #0000FF;">Y</span> <span style="color: #008000;">&lt;-</span> <span style="color: #FF0000;">200.0</span>
let v2 <span style="color: #008000;">=</span> VectorHV<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
v2<span style="color: #008000;">.</span><span style="color: #0000FF;">Horizontal</span> <span style="color: #008000;">&lt;-</span> <span style="color: #FF0000;">300.0</span>
v2<span style="color: #008000;">.</span><span style="color: #0000FF;">Vertical</span> <span style="color: #008000;">&lt;-</span> <span style="color: #FF0000;">400.0</span></pre></div></div>

<p>Each of the created types is a real compile-time type, with type safety enforced by the F# compiler.  For example, if the type provider supplies a dot product operation with vectors of the same kind (only), the F# compiler will check that the user doesn&#8217;t take dot products between vectors of different kinds:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let v1 <span style="color: #008000;">=</span> Vector2D<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
let v2 <span style="color: #008000;">=</span> Vector2D<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
let vh <span style="color: #008000;">=</span> VectorHV<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
&nbsp;
let v1v2 <span style="color: #008000;">=</span> v1<span style="color: #008000;">.</span><span style="color: #0000FF;">DotProduct</span><span style="color: #008000;">&#40;</span>v2<span style="color: #008000;">&#41;</span>  <span style="color: #008080; font-style: italic;">// okay</span>
let v1vh <span style="color: #008000;">=</span> v1<span style="color: #008000;">.</span><span style="color: #0000FF;">DotProduct</span><span style="color: #008000;">&#40;</span>vh<span style="color: #008000;">&#41;</span>  <span style="color: #008080; font-style: italic;">// type checks</span></pre></div></div>

<p>The created vector types work exactly as if you had written them longhand, but without all the effort, and without the limitation of having to guess what types your users will need.</p>
<p><strong>Implementing a type provider</strong></p>
<p>The F# team have indicated that they&#8217;ll be shipping the source for some sample type providers soon, which will include some handy helpers which should rather simplify the process of writing type providers, but for now it&#8217;s still not too difficult to implement type providers directly against the interfaces.  Here&#8217;s an outline, albeit with plenty of rough edges.</p>
<p>The first thing you need to do is create a F# 3.0 library project.  At the moment, this requires the <a href="http://www.microsoft.com/download/en/details.aspx?id=27543">Visual Studio 11 preview</a> (the full version, not the Metro apps version).  And you&#8217;ll need to apply TypeProviderAssemblyAttribute to that library:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span><span style="color: #008000;">&lt;</span>assembly<span style="color: #008000;">:</span> TypeProviderAssembly<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">do</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span></pre></div></div>

<p>Next, you&#8217;ll need to implement the type provider class itself.  This is a normal F# class which implements the ITypeProvider and IProvidedNamespace interfaces, and has the TypeProviderAttribute:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span><span style="color: #008000;">&lt;</span>TypeProvider<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#93;</span>
type VectorProvider<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span>
  <span style="color: #6666cc; font-weight: bold;">interface</span> ITypeProvider with <span style="color: #008080; font-style: italic;">// ...</span>
  <span style="color: #6666cc; font-weight: bold;">interface</span> IProvidedNamespace with <span style="color: #008080; font-style: italic;">// ...</span></pre></div></div>

<p>A type provider can provide multiple kinds of types, but for this example I&#8217;m going to assume that the provider only does Vector types.  This keeps my implementation simple because I don&#8217;t need to keep dispatching on &#8216;what kind of type is the user creating.&#8217;  This makes it pretty easy to implement IProvidedNamespace:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// Cheating for simplicity</span>
type Vector<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> inherit obj<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
&nbsp;
<span style="color: #008000;">&#91;</span><span style="color: #008000;">&lt;</span>TypeProvider<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#93;</span>
type VectorProvider<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span>
  <span style="color: #6666cc; font-weight: bold;">interface</span> IProvidedNamespace with
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ResolveTypeName</span><span style="color: #008000;">&#40;</span>typeName<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">typeof</span><span style="color: #008000;">&lt;</span>Vector<span style="color: #008000;">&gt;</span>
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">NamespaceName</span> with get<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Mindscape.Vectorama&quot;</span>
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetNestedNamespaces</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">&#91;</span><span style="color: #008000;">|</span> <span style="color: #008000;">|</span><span style="color: #008000;">&#93;</span>
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetTypes</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">&#91;</span><span style="color: #008000;">|</span> <span style="color: #008000;">typeof</span><span style="color: #008000;">&lt;</span>Vector<span style="color: #008000;">&gt;</span> <span style="color: #008000;">|</span><span style="color: #008000;">&#93;</span></pre></div></div>

<p>What&#8217;s that do-nothing Vector type for?  Well, when the user of the type provider writes <em>Vector&lt;&#8230;&gt;</em>, F# wants to interpret &#8220;Vector&#8221; as a type name.  The real type providers included with F# 3.0 create synthetic types to carry the desired provider names, but I&#8217;m too lazy to do that, so I&#8217;ve just created a dummy type to carry the name &#8220;Vector&#8221; for me.</p>
<p>For a simple demo, much of the ITypeProvider implementation can also be kept trivial:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span><span style="color: #008000;">&lt;</span>TypeProvider<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#93;</span>
type VectorProvider<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span>
  let invalidation <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #0600FF; font-weight: bold;">Event</span><span style="color: #008000;">&lt;</span>EventHandler, EventArgs<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
  <span style="color: #6666cc; font-weight: bold;">interface</span> ITypeProvider with
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetNamespaces</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">&#91;</span><span style="color: #008000;">|</span> <span style="color: #0600FF; font-weight: bold;">this</span> <span style="color: #008000;">|</span><span style="color: #008000;">&#93;</span>
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Dispose</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#91;</span><span style="color: #008000;">&lt;</span>CLIEvent<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#93;</span>
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Invalidate</span> <span style="color: #008000;">=</span> invalidation<span style="color: #008000;">.</span><span style="color: #0000FF;">Publish</span></pre></div></div>

<p>The meat of the type provider is in the remaining ITypeProvider methods: GetStaticParameters, ApplyStaticArguments and GetInvokerExpression.</p>
<p><strong>What can the user specify about the type?</strong></p>
<p>GetStaticParameters specifies what parameters the user can pass to the type provider when they create a type.  In our case, we want the user to be able to pass the names of the axes of their vector type &#8212; that is, the parameters are an arbitrary number of strings.  However, GetStaticParameters doesn&#8217;t have a way to indicate &#8220;any number of parameters,&#8221; so we have to settle for, for example, &#8220;you can pass 7 parameters, but they&#8217;re all optional.&#8221;  (In reality you&#8217;d make the first one mandatory, but I want to keep things simple.)  If we later need to support 8-dimensional vectors, we can simply update the limit in the type provider.  The parameters are going to become property names, so they need to be strings.  We&#8217;ll create a helper method to produce ParameterInfo objects with the right name, data type and optionality.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">module Helpers <span style="color: #008000;">=</span>
  let stringParameter index defaultVal <span style="color: #008000;">=</span>
    <span style="color: #008000;">&#123;</span> <span style="color: #008000;">new</span> ParameterInfo<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> with
      <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span> with get<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> sprintf <span style="color: #666666;">&quot;axis%d&quot;</span> index
      <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ParameterType</span> with get<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">typeof</span><span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span>
      <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Position</span> with get<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>
      <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">RawDefaultValue</span> with get<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> defaultVal
      <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DefaultValue</span> with get<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> defaultVal
      <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Attributes</span> with get<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> ParameterAttributes<span style="color: #008000;">.</span><span style="color: #0000FF;">Optional</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
open Helpers</pre></div></div>

<p>and then use this to specify what parameters the user can provide to the Vector type provider:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetStaticParameters</span><span style="color: #008000;">&#40;</span>typeWithoutArguments<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span>
  <span style="color: #008000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #008000;">..</span><span style="color: #FF0000;">7</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">|&gt;</span> List<span style="color: #008000;">.</span><span style="color: #0000FF;">map</span> <span style="color: #008000;">&#40;</span>fun i <span style="color: #008000;">-&gt;</span> stringParameter i <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">&#41;</span>
         <span style="color: #008000;">|&gt;</span> List<span style="color: #008000;">.</span><span style="color: #0000FF;">toArray</span></pre></div></div>

<p>This is enough to enable the user of our library to type Vector<"X", "Y"> with intellisense on the parameters.  Now we need to actually create a type to realise the user&#8217;s specification.</p>
<p><strong>Building the concrete type</strong></p>
<p>Building the type from the parameters provided by the user is the job of the ApplyStaticArguments method.  For the Vector demo, I&#8217;ll just create a class with properties named for each of the user parameters, and a DotProduct method.  (A better provider would create an immutable value type, but I want to keep it simple.)</p>
<p>At the moment, it seems that F# requires ApplyStaticArguments to create a physical assembly on disk.  If you build the type in memory, you get strange path errors.  I&#8217;m not sure if there&#8217;s a way around this, but for now I&#8217;ll just live with it and litter my temp directory with temporary assemblies.</p>
<p>So the code generator for vector types looks something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">module Helpers <span style="color: #008000;">=</span>
  let makeClass body name <span style="color: #008000;">=</span>
    let code <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;namespace Mindscape.Vectorama { public class &quot;</span> <span style="color: #008000;">+</span> name <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; {&quot;</span> <span style="color: #008000;">+</span> Environment<span style="color: #008000;">.</span><span style="color: #0000FF;">NewLine</span> <span style="color: #008000;">+</span> body <span style="color: #008000;">+</span> Environment<span style="color: #008000;">.</span><span style="color: #0000FF;">NewLine</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;} }&quot;</span>
    let dllFile <span style="color: #008000;">=</span> <span style="color: #000000;">System.<span style="color: #0000FF;">IO</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">Path</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetTempFileName</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    let csc <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Microsoft<span style="color: #008000;">.</span><span style="color: #0000FF;">CSharp</span><span style="color: #008000;">.</span><span style="color: #0000FF;">CSharpCodeProvider</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    let parameters <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #000000;">System.<span style="color: #0000FF;">CodeDom</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Compiler</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">CompilerParameters</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    parameters<span style="color: #008000;">.</span><span style="color: #0000FF;">OutputAssembly</span> <span style="color: #008000;">&lt;-</span> dllFile
    parameters<span style="color: #008000;">.</span><span style="color: #0000FF;">CompilerOptions</span> <span style="color: #008000;">&lt;-</span> <span style="color: #666666;">&quot;/t:library&quot;</span>
    <span style="color: #008080; font-style: italic;">// Ignoring error checking</span>
    let compilerResults <span style="color: #008000;">=</span> csc<span style="color: #008000;">.</span><span style="color: #0000FF;">CompileAssemblyFromSource</span><span style="color: #008000;">&#40;</span>parameters, <span style="color: #008000;">&#91;</span><span style="color: #008000;">|</span> code <span style="color: #008000;">|</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span>
    let asm <span style="color: #008000;">=</span> compilerResults<span style="color: #008000;">.</span><span style="color: #0000FF;">CompiledAssembly</span>
    asm<span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Mindscape.Vectorama.&quot;</span> <span style="color: #008000;">+</span> name<span style="color: #008000;">&#41;</span>
  let makeVector name argnames <span style="color: #008000;">=</span>
    let propNames <span style="color: #008000;">=</span> argnames <span style="color: #008000;">|&gt;</span> Seq<span style="color: #008000;">.</span><span style="color: #0000FF;">filter</span> <span style="color: #008000;">&#40;</span>fun arg <span style="color: #008000;">-&gt;</span> arg <span style="color: #008000;">&lt;&gt;</span> <span style="color: #0600FF; font-weight: bold;">null</span> <span style="color: #008000;">&amp;&amp;</span> not <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">String</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IsNullOrWhiteSpace</span><span style="color: #008000;">&#40;</span>arg<span style="color: #008000;">.</span><span style="color: #0000FF;">ToString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                             <span style="color: #008000;">|&gt;</span> Seq<span style="color: #008000;">.</span><span style="color: #0000FF;">map</span> <span style="color: #008000;">&#40;</span>fun arg <span style="color: #008000;">-&gt;</span> arg<span style="color: #008000;">.</span><span style="color: #0000FF;">ToString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                             <span style="color: #008000;">|&gt;</span> Seq<span style="color: #008000;">.</span><span style="color: #0000FF;">toList</span>
    let props <span style="color: #008000;">=</span> propNames <span style="color: #008000;">|&gt;</span> List<span style="color: #008000;">.</span><span style="color: #0000FF;">map</span> <span style="color: #008000;">&#40;</span>fun arg <span style="color: #008000;">-&gt;</span> <span style="color: #666666;">&quot;public double &quot;</span> <span style="color: #008000;">+</span> arg <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; { get; set; }&quot;</span><span style="color: #008000;">&#41;</span>
                          <span style="color: #008000;">|&gt;</span> <span style="color: #6666cc; font-weight: bold;">String</span><span style="color: #008000;">.</span><span style="color: #0000FF;">concat</span> Environment<span style="color: #008000;">.</span><span style="color: #0000FF;">NewLine</span>
    let dotProductBody <span style="color: #008000;">=</span> propNames <span style="color: #008000;">|&gt;</span> List<span style="color: #008000;">.</span><span style="color: #0000FF;">map</span> <span style="color: #008000;">&#40;</span>fun arg <span style="color: #008000;">-&gt;</span> sprintf <span style="color: #666666;">&quot;this.%s * other.%s&quot;</span> arg arg<span style="color: #008000;">&#41;</span>
                                   <span style="color: #008000;">|&gt;</span> <span style="color: #6666cc; font-weight: bold;">String</span><span style="color: #008000;">.</span><span style="color: #0000FF;">concat</span> <span style="color: #666666;">&quot; + &quot;</span>
    let dotProduct <span style="color: #008000;">=</span> sprintf <span style="color: #666666;">&quot;public double DotProduct(%s other) { return %s; }&quot;</span> name dotProductBody
    let body <span style="color: #008000;">=</span> props <span style="color: #008000;">+</span> Environment<span style="color: #008000;">.</span><span style="color: #0000FF;">NewLine</span> <span style="color: #008000;">+</span> dotProduct
    makeClass body name</pre></div></div>

<p>This isn&#8217;t as intimidating as it looks!  The makeClass function wraps a code string in a namespace and class declaration, compiles it and returns the compiled type.  The makeVector function removes empty parameters (remember we had to permit lots of parameters but defaulted unused ones to be blank), then spits out a property for each surviving parameter, and a DotProduct method generated by iterating over the parameters.</p>
<p>It turns out that makeVector is pretty much all we need to implement ApplyStaticArguments.  The F# compiler tells us the name of the type the user wants us to provide, and the list of parameters supplied by the user, and all we need to do is pass them on to makeVector:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ApplyStaticArguments</span><span style="color: #008000;">&#40;</span>typeWithoutArguments, typeNameWithArguments, staticArguments<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span>
  makeVector typeNameWithArguments staticArguments</pre></div></div>

<p><strong>Compiling property and method calls to the created type</strong></p>
<p>We are nearly there!  Our type provider now provides types to the user on demand, but the user will still get errors if they try to instantiate or invoke those types.  GetInvokerExpression is the final piece of the jigsaw, the piece which tells the F# compiler how to generate code for method invocations on the generated type.  It&#8217;s not yet clear to me how comprehensive GetInvokerExpression has to be, but for the simple Vector example, we just need to handle a couple of cases &#8212; construction and method invocation:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetInvokerExpression</span><span style="color: #008000;">&#40;</span>syntheticMethodBase, parameters<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span>
  match syntheticMethodBase with
  <span style="color: #008000;">|</span> <span style="color: #008000;">:?</span> ConstructorInfo <span style="color: #0600FF; font-weight: bold;">as</span> ctor <span style="color: #008000;">-&gt;</span> Expression<span style="color: #008000;">.</span><span style="color: #008000;">New</span><span style="color: #008000;">&#40;</span>ctor<span style="color: #008000;">&#41;</span> <span style="color: #008000;">:&gt;</span> Expression
  <span style="color: #008000;">|</span> <span style="color: #008000;">:?</span> MethodInfo <span style="color: #0600FF; font-weight: bold;">as</span> mi <span style="color: #008000;">-&gt;</span> let args <span style="color: #008000;">=</span> parameters <span style="color: #008000;">|&gt;</span> Seq<span style="color: #008000;">.</span><span style="color: #0000FF;">skip</span> <span style="color: #FF0000;">1</span> <span style="color: #008000;">|&gt;</span> Seq<span style="color: #008000;">.</span><span style="color: #0000FF;">cast</span><span style="color: #008000;">&lt;</span>Expression<span style="color: #008000;">&gt;</span>
                           Expression<span style="color: #008000;">.</span><span style="color: #0000FF;">Call</span><span style="color: #008000;">&#40;</span>parameters<span style="color: #008000;">.</span><span style="color: #008000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#93;</span>, mi, args<span style="color: #008000;">&#41;</span> <span style="color: #008000;">:&gt;</span> Expression
  <span style="color: #008000;">|</span> _ <span style="color: #008000;">-&gt;</span> let pnames <span style="color: #008000;">=</span> parameters <span style="color: #008000;">|&gt;</span> Seq<span style="color: #008000;">.</span><span style="color: #0000FF;">map</span> <span style="color: #008000;">&#40;</span>fun p <span style="color: #008000;">-&gt;</span> p<span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">|&gt;</span> <span style="color: #6666cc; font-weight: bold;">String</span><span style="color: #008000;">.</span><span style="color: #0000FF;">concat</span> <span style="color: #666666;">&quot;, &quot;</span>
         failwith <span style="color: #008000;">&#40;</span>sprintf <span style="color: #666666;">&quot;ERROR: Don't know what to do in GetInvokerExpression - %s(%s)&quot;</span> syntheticMethodBase<span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span> pnames<span style="color: #008000;">&#41;</span></pre></div></div>

<p>The most alarming bit about this code is probably the strange F# type operators.  We&#8217;re just seeing whether F# wants to compile a constructor or a method call, packaging up the appropriate expression tree, then upcasting to the Expression base type to stop F# whining about type mismatches.</p>
<p><strong>And we&#8217;re done!</strong></p>
<p>Well, okay, there&#8217;s a lot of tidying up to do.  But hopefully the samples promised by the F# team will help with that.  And at any rate we now have a Vector library that users can use to define Vector types of arbitrary complexity (well, up to 7 dimensions anyway) with a single line of code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span><span style="color: #008000;">&lt;</span>Generate<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#93;</span>
type Vector3D <span style="color: #008000;">=</span> Vector<span style="color: #008000;">&lt;</span><span style="color: #666666;">&quot;X&quot;</span>, <span style="color: #666666;">&quot;Y&quot;</span>, <span style="color: #666666;">&quot;Z&quot;</span><span style="color: #008000;">&gt;</span>
&nbsp;
let v3 <span style="color: #008000;">=</span> Vector3D<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
v3<span style="color: #008000;">.</span><span style="color: #0000FF;">X</span> <span style="color: #008000;">&lt;-</span> <span style="color: #FF0000;">1.0</span>
v3<span style="color: #008000;">.</span><span style="color: #0000FF;">Y</span> <span style="color: #008000;">&lt;-</span> <span style="color: #FF0000;">2.0</span>
v3<span style="color: #008000;">.</span><span style="color: #0000FF;">Z</span> <span style="color: #008000;">&lt;-</span> <span style="color: #FF0000;">3.0</span></pre></div></div>

<p>(If you count two lines of code here, well, fair enough, but the GenerateAttribute will be removed before the final release.)</p>
<p><strong>As if by magic&#8230;</strong></p>
<p>Obviously, the Vector example is pretty trivial, and for most applications it would be easier to write the boring Vector code longhand rather than writing a whole type provider.  But the possibilities for this seem endless.  Type providers don&#8217;t just have to be about data access.  In the same way as <a href="http://channel9.msdn.com/Events/TechEd/NewZealand/2011/DEV403?WT.mc_id=eml-n-nz-loc--tetofe">dynamic programming already enables users to create their own APIs without having to write their own implementations</a>, type providers allow users to create their own APIs without having to write their own implementations, but this time with all the benefits of type checking, intellisense and so on.  And of course type providers can be as sophisticated as you like, far more sophisticated than my simple example.</p>
<p>Oh, and one more thing.  Although only the F# compiler can invoke type providers, the types generated by the provider are real, compiled-in types.  That means you can use those types from C# or Visual Basic code just by referencing the F# project that declares them.</p>
<p>Yep, this is going to be pretty cool.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2011/09/19/f-type-providers-as-if-by-magic/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>F# Friday &#8211; 1 hour video presentation</title>
		<link>http://www.mindscapehq.com/blog/index.php/2011/09/01/f-friday-1-hour-video-presentation/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2011/09/01/f-friday-1-hour-video-presentation/#comments</comments>
		<pubDate>Fri, 02 Sep 2011 01:59:44 +0000</pubDate>
		<dc:creator>John-Daniel Trask</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Bearded]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=3722</guid>
		<description><![CDATA[So you lapped up Ivan&#8217;s Dynamic &#038; Meta Programming in .NET 4 earlier in the week? Thought it was a bit too easy going and want something to sink your teeth into this Friday afternoon? Look no further than Ivan&#8217;s presentation on F# programming! Watch the video online &#8211; be sure to rate it highly! [...]]]></description>
				<content:encoded><![CDATA[<p>So you lapped up <a href="http://www.mindscapehq.com/blog/index.php/2011/08/29/tech-ed-nz-wrap-up/" target="_blank">Ivan&#8217;s Dynamic &#038; Meta Programming in .NET 4</a> earlier in the week? Thought it was a bit too easy going and want something to sink your teeth into this Friday afternoon? Look no further than Ivan&#8217;s presentation on F# programming!</p>
<p><a href="http://channel9.msdn.com/Events/TechEd/NewZealand/2011/DEV311" target="_blank">Watch the video online &#8211; be sure to rate it highly!</a></p>
<p>What more could you want on a Friday afternoon? I mean, maybe a beer but&#8230;</p>
<p><strong>Question:</strong> Do you enjoy learning about F#? Would you be interested in an instructional series on how to work better with it? Drop us a comment if you&#8217;d be interested!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2011/09/01/f-friday-1-hour-video-presentation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Polyglot programming &#8211; some lessons learned</title>
		<link>http://www.mindscapehq.com/blog/index.php/2011/07/21/polyglot-programming-some-lessons-learned/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2011/07/21/polyglot-programming-some-lessons-learned/#comments</comments>
		<pubDate>Fri, 22 Jul 2011 01:00:04 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=3535</guid>
		<description><![CDATA[With Web Workbench now safely out the door, I thought I&#8217;d share some lessons learned from its development. (Rest assured you don&#8217;t need to know any of this stuff to use Web Workbench.) One unusual aspect of the development of Web Workbench is the number of languages we used to develop it. Like most .NET [...]]]></description>
				<content:encoded><![CDATA[<p>With <a href="http://www.mindscapehq.com/products/web-workbench">Web Workbench</a> now safely out the door, I thought I&#8217;d share some lessons learned from its development.  (Rest assured you don&#8217;t need to know any of this stuff to <em>use</em> Web Workbench.)</p>
<p>One unusual aspect of the development of Web Workbench is the number of languages we used to develop it.  Like most .NET projects, it contains a fair chunk of C#.  But quite a bit of the core is written in F#, and it also invokes a large amount of external Ruby and JavaScript code.  While using all these languages definitely made it far easier to develop the product, it did also throw up a few challenges and surprises.</p>
<h3 style="font-size: 150%">How Web Workbench fits together</h3>
<p>Web Workbench consists of three major chunks: the language parsers, which work out the information needed for syntax highlighting, intellisense and so on; the third-party compilers, which generate the output CSS and JavaScript files; and the Visual Studio integration, which surfaces these capabilities in the Visual Studio UI.</p>
<p>We chose C# to implement the Visual Studio integration, mainly because the tooling for developing Visual Studio components is C#/VB-centric, and there weren&#8217;t any compelling reasons to use anything else.  So the rest of this review is from the point of view of integrating non-C# components into a C# framework.</p>
<h3 style="font-size: 150%">F#</h3>
<p><a href="http://msdn.microsoft.com/en-us/fsharp/cc742182">F#</a> is a functional language modelled on OCaml.  After shipping from Microsoft Research for several years, it is now included in Visual Studio 2010 out of the box.  We used F# to implement the parser components of Web Workbench.</p>
<p>We chose F# for a couple of reasons.  The first was that constructs like discriminated unions, records and pattern matching would reduce the amount of boring boilerplate code we had to write.  In particular, they provide a great way to quickly represent and traverse an abstract syntax tree (AST).  The second was the availability of parser libraries.  For a previous project we used fslex and fsyacc, external parser generation tools which come with the <a href="http://fsharppowerpack.codeplex.com/">F# PowerPack</a>.  For Web Workbench we switched over to Stephan Tolksdorf&#8217;s beautiful parser combinator libary, <a href="http://www.quanttec.com/fparsec/tutorial.html">FParsec</a>.  FParsec made it easy to build up higher-level constructs such as &#8220;pair&#8221; or &#8220;with position&#8221; and to parameterise parsers for example to reflect the different prefixes for variables in Sass and Less.  It&#8217;s probably a subject for a separate blog post, but FParsec alone is a compelling reason to use F# for this kind of project!</p>
<p>Interoperating F# with C# is mostly pretty easy.  F# assemblies are normal .NET assemblies and expose classes and functions in the standard way.  However, there are a few wrinkles and inconveniences.</p>
<p><strong>Discriminated union members</strong></p>
<p>Suppose you define a <a href="http://msdn.microsoft.com/en-us/library/dd233226.aspx">discriminated union</a> in F# along the lines of:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">type AstNode <span style="color: #008000;">=</span>
<span style="color: #008000;">|</span> SelectorNode of <span style="color: #6666cc; font-weight: bold;">string</span> <span style="color: #008000;">*</span> AstNode list
<span style="color: #008000;">|</span> ErrorNode of <span style="color: #6666cc; font-weight: bold;">string</span>
<span style="color: #008000;">|</span> OtherNode</pre></div></div>

<p>In C#, you&#8217;ll see an AstNode base class, with derived nested classes named SelectorNode and ErrorNode, and a property named OtherNode.  ErrorNode has a single property named Item, and SelectorNode has properties named Item1 and Item2.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> AstNode
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> SelectorNode
  <span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> Item1 <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> FSharpList<span style="color: #008000;">&lt;</span>AstNode<span style="color: #008000;">&gt;</span> Item2 <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
  <span style="color: #008000;">&#125;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> ErrorNode
  <span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> Item <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
  <span style="color: #008000;">&#125;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> AstNode OtherNode <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>If you find yourself working with these classes from C#, the names are pretty unmemorable and you need to be careful about maintenance as you add or remove members.  It&#8217;s therefore worth thinking carefully about how to partition work between the two languages.  Ideally you want C# to be able to treat the F# classes as opaque objects, so that whenever it needs to do anything with them, it hands them back to F#.</p>
<p>This isn&#8217;t always practical, though.  In particular, when unit testing the parser, we wanted to be able to make assertions about the AST that results from a given input.  We could have written the tests in F#, but the tooling for unit testing is much better in C#.  So instead we wrote a bunch of extension methods for the various AST node types that mapped directly onto the Item members, and this seemed to work pretty well.</p>
<p>This was only for tests, and our production code managed to almost entirely avoid peeking into the structure of AST nodes, by dint of writing most node processing code in F#.</p>
<p><strong>F# and C# functions</strong></p>
<p>One issue that this raised was passing C# functions into F#.  For example, our AST traversal code, which needed to understand the structure of AST node types, was written in F#, but one of its arguments was a visitor function, and sometimes we needed that visitor function to be written in C# because it was part of the Visual Studio integration framework.  Unfortunately, C# passes function arguments as delegates, whereas F# expects function arguments to be of F# function types.  (Internally, F# doesn&#8217;t represent function types as delegates &#8212; it has its own function type named FSharpFunc.)</p>
<p>To get around this, we created a C#-friendly version of the traversal function, which took a delegate, created a F# lambda to call that delegate, and passed that F# lambda to the real traversal function.  Another handy tool is the FSharpFunc.FromConverter function, which is a built-in way to convert a delegate to a F# function.</p>
<p><strong>Options and lists</strong></p>
<p>I generally refer to the F# <a href="http://msdn.microsoft.com/en-us/library/dd233245.aspx">option</a> type as &#8220;nullable types done right&#8221; &#8212; safer and more self-documenting than null references or nullable value types.  Using a F# option from C# is pretty easy, but building them is rather ugly.  In the few cases where one of our integration points took an option, we implemented a builder functions in F# to avoid having to write out direct invocations to the FSharpOption type.</p>
<p>The experience with F# lists was pretty similar.  Throwing a ToList() at a FSharpList quickly got rid of the F#-ness when we were consuming them, but building them is something you just don&#8217;t want to do in C#.</p>
<p><strong>Dependencies</strong></p>
<p>One small but annoying surprise we got when we shipped Web Workbench was that, by default, the FSharp.Core runtime doesn&#8217;t get copied locally &#8212; but that the Visual Studio installer skips the F# redistributables if the user chooses not to install F#.  This led to some hard-to-reproduce errors.  So set FSharp.Core to copy local, or use the compiler &#8220;standalone&#8221; flag, even for VSIX projects.</p>
<h3 style="font-size: 150%">Ruby</h3>
<p>The <a href="http://sass-lang.com/">Sass</a> compiler is built in Ruby, and naturally we wanted to use it as it stood rather than rewriting it.  In fact, we originally planned to use the Ruby compiler to do our parsing, but we found it was not fast enough to keep up with users typing, and it stopped after the first error, whereas we need to recover in order to provide syntax highlighting on the rest of the document even after an error.  (Especially since the document would spend a lot of its time in error while the user was in the middle of typing something!)  So we dropped back to implementing our own parser for real-time aspects such as highlighting and intellisense, but still wanted to use the real compiler to ensure full fidelity &#8212; and to save ourselves a lot of effort!</p>
<p><strong>Deployment</strong></p>
<p>To avoid requiring our users to install Ruby and Sass, we decided to use <a href="http://ironruby.net/">IronRuby</a>, Microsoft&#8217;s implementation of Ruby on .NET, to run the compiler.  This allowed us to xcopy deploy IronRuby as part of the Web Workbench VSIX, obviating the need for a separate install (and coincidentally ensuring we controlled which version of IronRuby we ran under!).</p>
<p>However, IronRuby depends at runtime a bunch of Ruby library source files.  Similarly, Sass ships as a whole tree of Ruby source files.  We needed to ensure that all these files were available at runtime, and xcopy assembly deployment wasn&#8217;t going to handle that for us.  We could have included these source files in the VSIX directly, but this would have been very heavy maintenance because of the number of files.  Our solution was to create zip files of the IronRuby and Sass trees, and unzip these at runtime.  This incurs a small overhead the first time the compiler runs, but in practice this isn&#8217;t significant.</p>
<p>One small but crucial detail is that since IronRuby is being hosted as a DLL rather than running from the command line, it needs to be told where to find the unzipped runtime files.  This involves a call to ScriptEngine.SetSearchPaths.</p>
<p><strong>Strings</strong></p>
<p>The .NET <a href="http://msdn.microsoft.com/en-us/library/dd233052.aspx">Dynamic Language Runtime</a> generally tries to map common CLR types such as integers and strings to the corresponding types in the language at hand.  For the most part, this works pretty transparently, but sometimes the mismatch can throw up some odd errors.  For example, when we set the Sass :load_paths option so that it could resolve @imported files, we started seeing weird &#8220;wrong number of arguments (2 for 1)&#8221; errors from the Sass compiler.</p>
<p>In IronRuby, strings should be represented as the built-in MutableString type.  However, when using APIs such as ScriptScope.SetVariable, it&#8217;s possible to pass a .NET string.  IronRuby won&#8217;t complain about this, and most of the time it will work.  We&#8217;re not sure exactly what went wrong on the Sass :load_paths case, but we suspect it may have passed an <strong>is_a? String</strong> test despite not being a true mutable Ruby string.  So the lesson is always to wrap strings using MutableString.CreateAscii before passing them to SetVariable.</p>
<p>A similar issue applies to strings returned from Ruby scripts.  You can&#8217;t cast them to .NET strings, because they are instances of MutableString rather than String.  Use ToString() instead.</p>
<p><strong>Ruby versioning and compatibility</strong></p>
<p>IronRuby 1.1.1 implements Ruby 1.9.  However, although the implementation is &#8216;complete enough for Rails,&#8217; it&#8217;s not 100% complete.  We got a nasty surprise when the Sass compiler started raising missing method exceptions.  There&#8217;s a place in Sass where it calls the chr function.  Under 1.8 it calls this on a Fixnum, but when it thinks it&#8217;s running under 1.9, it calls it on a String.  And IronRuby 1.1.1 doesn&#8217;t implement String.chr.</p>
<p>We were able to solve this problem fairly quickly once we&#8217;d identified it, by running some Ruby code during initialisation to re-open the String class and add the missing chr method.  The lesson is more to be aware that third-party implementations of Ruby may not be 100% compatible &#8212; and again to carefully read exception messages!</p>
<p>(In most cases, Sass does detect IronRuby and falls back to 1.8 behaviour &#8212; this just seems to be a case that slipped through the net, but I thought I&#8217;d mention it because other Ruby libraries may not be aware of IronRuby&#8217;s quirks the way Sass is.)</p>
<p><strong>Exceptions</strong></p>
<p>Talking of exceptions, we struggled for a while to get meaningful error information out of Sass syntax error exceptions.  This wasn&#8217;t because Sass didn&#8217;t provide the information, it was just that IronRuby didn&#8217;t make it easy to find.  There are a couple of tricks to be aware of here.</p>
<p>First, the Ruby exception data isn&#8217;t presented as a nice simple property on the exception object.  Instead, you need to call a static method on RubyExceptionData.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">RubyExceptionData rubyException <span style="color: #008000;">=</span> RubyExceptionData<span style="color: #008000;">.</span><span style="color: #0000FF;">GetInstance</span><span style="color: #008000;">&#40;</span>ex<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Once you have a RubyExceptionData object, you can get the Ruby backtrace, which is invaluable for diagnostics!</p>
<p>Second, when Sass sets exception attributes such as the line number in the SCSS source file, these are available as dynamic properties, but it&#8217;s not always obvious what dynamic property you need.  I found the following snippet useful for listing the members available on an IronRuby exception that had propagated up into C#:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span><span style="color: #000000;">System</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Dynamic</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IDynamicMetaObjectProvider</span><span style="color: #008000;">&#41;</span>ex<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetMetaObject</span><span style="color: #008000;">&#40;</span><span style="color: #000000;">System</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Linq</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Expressions</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Expression</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Constant</span><span style="color: #008000;">&#40;</span>ex<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetDynamicMemberNames</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span></pre></div></div>

<p>(The fully qualified type names are so that you can paste it into the Visual Studio Immediate window while debugging.)  Armed with the list of Ruby members it was usually easy to figure out the dynamic call I needed:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">object</span> scssLine <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>dynamic<span style="color: #008000;">&#41;</span>ex<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">sass_line</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h3 style="font-size: 150%">JavaScript</h3>
<p>In the same way as we run the real Ruby Sass compiler on our SCSS files, we run the real JavaScript <a href="http://jashkenas.github.com/coffee-script/">CoffeeScript</a> compiler on our CoffeeScript files.  We looked at three options for this: running on <a href="http://nodejs.org/">Node.js</a> under Cygwin, running on the DLR using <a href="https://github.com/fholm/IronJS">IronJS</a>, and running on a ground-up implementation using <a href="http://jurassic.codeplex.com/">Jurassic</a>.  The Node approach turned out awfully kludgy, involving as it did launching a separate process through an exciting collection of command scripts, so as with Ruby we turned to the DLR.  Unfortunately, IronJS wasn&#8217;t able to run the CoffeeScript compiler (though the team are looking at the issue and I believe they now have a fix), so Jurassic it was.  Jurassic uses a lot of the same terminology as the DLR so it&#8217;s a familiar programming experience, but it doesn&#8217;t actually use the DLR under the covers so you can&#8217;t use DLR tricks like <a href="http://msdn.microsoft.com/en-us/library/dd264736.aspx">C# dynamic</a> and <a href="http://msdn.microsoft.com/en-us/library/system.dynamic.idynamicmetaobjectprovider.aspx">IDynamicMetaObjectProvider</a> against it.</p>
<p>Still, running the compiler under Jurassic worked nicely.  The CoffeeScript compiler is available as a standalone JavaScript file: we could just load that in from a file or string resource and we were good to go.  However, as we had initially planned with Sass, we also wanted to use the CoffeeScript parser rather than writing our own, and that turned out to be a bit more challenging, as we could no longer use the standalone compiler &#8212; and the &#8216;non-standalone&#8217; version worked only on Node.</p>
<p><strong>Running Node modules under Jurassic</strong></p>
<p>The solution we adopted was to implement enough of the Node environment to make the CoffeeScript parser happy.  Fortunately, there wasn&#8217;t very much of this: in fact, it turned out all we needed to do was implement the <strong>require</strong> function, which the CoffeeScript parser uses to read in the other files it depends on such as the lexer.</p>
<p>This was reasonably easy to do using Jurassic&#8217;s ScriptEngine.SetGlobalFunction method.  This allowed us to implement file content resolution in C# or F#, where we had access to the System.IO and System.Resources APIs, and assign that resolution function to the name &#8216;require.&#8217;  Then JavaScript calls to <strong>require</strong> would end up getting handled by the host function, which loaded the content of the &#8216;required&#8217; file, passed it back to Jurassic to be executed and captured the results to be returned to the requirer.</p>
<p>The technique of mapping Node externals to host functions should allow arbitrary Node modules to be run under Jurassic, though it could require a fair bit of work if the module has a lot of Node-specific dependencies!</p>
<p><strong>Strings</strong></p>
<p>Similar to Ruby, strings returned from JavaScript aren&#8217;t always .NET System.Strings.  (Sometimes they are, sometimes they aren&#8217;t.  It depends on how they were constructed inside the JavaScript code.)  Again, use ToString() rather than trying to cast to string.</p>
<p><strong>Strange things in close up</strong></p>
<p>JavaScript is famed for its quirks and pitfalls, and Jurassic makes it easy to enjoy them in the usually drearily regular setting of the CLR.  For example, would you guess that these do the same thing?</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">engine<span style="color: #008000;">.</span><span style="color: #0000FF;">Execute</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;a = { }&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
engine<span style="color: #008000;">.</span><span style="color: #0000FF;">SetGlobalValue</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;a&quot;</span>, engine<span style="color: #008000;">.</span><span style="color: #0000FF;">Evaluate</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;{ }&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Of course they don&#8217;t.  The first sets <strong>a</strong> to an empty object, as you would expect.  The second sets <strong>a</strong> to undefined.  So when injecting code into Jurassic from the host, watch out for JavaScript evaluation quirks!</p>
<h3 style="font-size: 150%">Conclusion</h3>
<p>The polyglot approach is tremendously powerful, but inevitably the integration isn&#8217;t completely seamless.  That&#8217;s probably unrealistic: different languages have different conceptual models, and different semantics even for supposedly common types such as strings.</p>
<p>I&#8217;m conscious that this article has focused on the difficulties and surprises, and I want to re-emphasise that the polyglot approach was definitely a net win for us.  We simply could not have delivered Web Workbench as a monolingual program.  The parsers that underlie the syntax highlighting and intellisense would have been much harder to develop, even with the help of a C#-friendly toolkit like ANTLR, and we couldn&#8217;t even have attempted the compilers.  I guess we could have shelled out to Ruby and Node but the deployment issues would have been horrible, and of course that&#8217;s really just concealing the polyglot nature rather than getting rid of it.</p>
<p>The boundaries between the C# and the Ruby/JavaScript code were pretty well defined and well bounded.  Integrating our own F# code into C# was a more interesting design exercise: as I mentioned, some idioms don&#8217;t translate well, so identifying the right boundary between the two languages is very important to keeping each side idiomatic and avoiding warts like delegates in F# and ItemX calls in C#.  We end up shuttling things back and forth across the language boundary quite a lot in order to do the right processing in the right place, but the experience is generally pretty seamless.</p>
<p>Based on our experience with Web Workbench, polyglot programming isn&#8217;t something you should do lightly.  If you&#8217;ve only got one or two files that would be better off as F# or Ruby or JavaScript, then it&#8217;s probably more efficient to port them to your language of choice than to deal with the integration and deployment issues.  But it&#8217;s nothing to be afraid of, either.  In this post I&#8217;ve tried to alert you to some of the things you&#8217;ll encounter and how we solved them, but I&#8217;ve also tried to emphasise that the difficulties were outweighed by the benefits.  We hope this will encourage you to keep your eyes open for places where polyglot programming can help you too!</p>
<p>If you enjoyed this article, please <a href="http://news.ycombinator.com/item?id=2791977">consider voting for it on Hacker News</a> &#8212; thanks!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2011/07/21/polyglot-programming-some-lessons-learned/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Object expressions in F#</title>
		<link>http://www.mindscapehq.com/blog/index.php/2011/03/17/object-expressions-in-f/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2011/03/17/object-expressions-in-f/#comments</comments>
		<pubDate>Thu, 17 Mar 2011 05:36:58 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=2951</guid>
		<description><![CDATA[Today I&#8217;ve been building a simple auditing feature for LightSpeed which automatically logs who created, deleted or last modified an entity. One of the wrinkles in this feature is of course that the way to get the username differs from application to application: in a Windows client application, it might be the logged-on user, but [...]]]></description>
				<content:encoded><![CDATA[<p>Today I&#8217;ve been building a simple auditing feature for LightSpeed which automatically logs who created, deleted or last modified an entity.  One of the wrinkles in this feature is of course that the way to get the username differs from application to application: in a Windows client application, it might be the logged-on user, but in a Web application with Forms authentication we&#8217;d want it to be the HttpContext user rather than the operating system user account.  Obviously, this is a great fit for the strategy pattern, and that&#8217;s exactly what I used: I defined an interface for getting the current user, and built Windows client and ASP.NET implementations of that interface.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">internal</span> <span style="color: #6666cc; font-weight: bold;">class</span> WindowsIdentityAuditInfoStrategy <span style="color: #008000;">:</span> IAuditInfoStrategy
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> IAuditInfoStrategy Instance <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> WindowsIdentityAuditInfoStrategy<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF; font-weight: bold;">private</span> WindowsIdentityAuditInfoStrategy<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #008000;">&#125;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> AuditInfoMode Mode <span style="color: #008000;">&#123;</span> get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> AuditInfoMode<span style="color: #008000;">.</span><span style="color: #0000FF;">WindowsIdentity</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span> <span style="color: #008000;">&#125;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> GetCurrentUser<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #008080; font-style: italic;">/* super-secret Mindscape proprietary code */</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The annoying thing about this is that I don&#8217;t really need all the overhead of a class, and could also do without the trickery required to make it a singleton.  What I&#8217;d really like to do is declare an <em>object</em> that implements the interface.  That would save me writing all the class verbiage, and also make it clearer to readers of my code that the object was a singleton.</p>
<p>If I&#8217;d been using F#, I could have done exactly this.  F# has a feature called <em>object expressions</em>, which basically allow you to create an object with members and behaviour, without creating a class to contain those members and behaviour.  Let&#8217;s look at an example.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let windowsIdentityAuditInfoStrategy <span style="color: #008000;">=</span> <span style="color: #008000;">&#123;</span>
  <span style="color: #008000;">new</span> IAuditInfoStrategy with
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Mode</span> <span style="color: #008000;">=</span> AuditInfoMode<span style="color: #008000;">.</span><span style="color: #0000FF;">WindowsIdentity</span>
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrentUser</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> WindowsIdentity<span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrent</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span> <span style="color: #008000;">&#125;</span>  <span style="color: #008080; font-style: italic;">// oh no!  I gave it away!</span>
&nbsp;
printfn <span style="color: #666666;">&quot;%A&quot;</span> <span style="color: #008000;">&#40;</span>windowsIdentityAuditInfoStrategy<span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrentUser</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008080; font-style: italic;">// prints &quot;athena\Ivan&quot;</span></pre></div></div>

<p>What&#8217;s going on here?  That opening brace followed by <em>new IAuditInfoStrategy</em> tells F# that this is an object expression: that I want an object that implements IAuditInfoStrategy as shown.  F# obligingly creates a suitable object by some nefarious means which I don&#8217;t have to worry about, and returns it into my variable.</p>
<p>Object expressions aren&#8217;t limited to interfaces.  You can use them whenever you want to inject a bit of implementation without creating a whole new type:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let purportedDromedary <span style="color: #008000;">=</span> <span style="color: #008000;">&#123;</span>
  <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">Object</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> with
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ToString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;I'm a dromedary&quot;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
printfn <span style="color: #666666;">&quot;%A&quot;</span> purportedDromedary
<span style="color: #008080; font-style: italic;">// prints I'm a dromedary</span></pre></div></div>

<p>Nor are they limited to singletons.  In fact a handy feature of F# object expressions is that they can capture local variables, just like closures do:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let purported thingy <span style="color: #008000;">=</span> <span style="color: #008000;">&#123;</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">Object</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> with member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ToString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;I'm a &quot;</span> <span style="color: #008000;">+</span> thingy <span style="color: #008000;">&#125;</span>
&nbsp;
printfn <span style="color: #666666;">&quot;%A&quot;</span> <span style="color: #008000;">&#40;</span>purported <span style="color: #666666;">&quot;wildebeeste&quot;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008080; font-style: italic;">// prints I'm a wildebeeste</span>
printfn <span style="color: #666666;">&quot;%A&quot;</span> <span style="color: #008000;">&#40;</span>purported <span style="color: #666666;">&quot;trask&quot;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008080; font-style: italic;">// prints I'm a trask</span></pre></div></div>

<p>Obviously impersonating equatorial wildlife is fairly specialised as business requirements go, so let&#8217;s go back to the auditing example.  In LightSpeed, the IAuditInfoStrategy is public, so that customers can implement their own application-specific user identification strategies.  Perhaps the application has its own custom security system.  Perhaps it is integrated into Lotus Notes&#8211; but no, some things are too horrible to contemplate.  Regardless, we might find it useful to define a common base class for custom strategies:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span><span style="color: #008000;">&lt;</span>AbstractClass<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#93;</span>
type CustomAuditInfoStrategy<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span>
  <span style="color: #6666cc; font-weight: bold;">interface</span> IAuditInfoStrategy with
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Mode</span> <span style="color: #008000;">=</span> AuditInfoMode<span style="color: #008000;">.</span><span style="color: #0000FF;">Custom</span>
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrentUser</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrentUserCore</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
  abstract member GetCurrentUserCore <span style="color: #008000;">:</span> unit <span style="color: #008000;">-&gt;</span> <span style="color: #6666cc; font-weight: bold;">string</span></pre></div></div>

<p>So far, this is just a normal F# abstract class, to save us having to reimplement Mode every time.  Let&#8217;s put it to the all-important work of making someone else carry the can:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let blame x <span style="color: #008000;">=</span> <span style="color: #008000;">&#123;</span>
  <span style="color: #008000;">new</span> CustomAuditInfoStrategy<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> with
    member <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrentUserCore</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> x <span style="color: #008000;">&#125;</span></pre></div></div>

<p>What does the <em>blame</em> function do?  It creates a new CustomAuditInfoStrategy whose GetCurrentUserCore method always returns our designated scapegoat.  Notice that we haven&#8217;t had to create a ScapegoatingStrategy class to contain this brutal but realistic business logic: we can do it inline in the <em>blame</em> function.  This keeps the blaming logic within the blame function instead of spinning it out to a separate location.  And of course we can call the function multiple times to shift the blame around as required.  Let&#8217;s try it out:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let context <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> LightSpeedContext<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
context<span style="color: #008000;">.</span><span style="color: #0000FF;">AuditInfoMode</span> <span style="color: #008000;">&lt;-</span> AuditInfoMode<span style="color: #008000;">.</span><span style="color: #0000FF;">Custom</span>
&nbsp;
context<span style="color: #008000;">.</span><span style="color: #0000FF;">CustomAuditInfoStrategy</span> <span style="color: #008000;">&lt;-</span> blame <span style="color: #666666;">&quot;bob&quot;</span>
printfn <span style="color: #666666;">&quot;%A&quot;</span> <span style="color: #008000;">&#40;</span>context<span style="color: #008000;">.</span><span style="color: #0000FF;">CustomAuditInfoStrategy</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrentUser</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008080; font-style: italic;">// prints &quot;bob&quot;</span>
&nbsp;
context<span style="color: #008000;">.</span><span style="color: #0000FF;">CustomAuditInfoStrategy</span> <span style="color: #008000;">&lt;-</span> blame <span style="color: #666666;">&quot;kate&quot;</span>
printfn <span style="color: #666666;">&quot;%A&quot;</span> <span style="color: #008000;">&#40;</span>context<span style="color: #008000;">.</span><span style="color: #0000FF;">CustomAuditInfoStrategy</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrentUser</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008080; font-style: italic;">// prints &quot;kate&quot;</span></pre></div></div>

<p>Of course, under the surface, the F# compiler is defining derived classes of CustomAuditInfoStrategy just as you would if you were implementing this in C#.  (Load the compiled F# code into a C# decompiler such as Reflector if you want to see what&#8217;s really going on.)  But at the source code level, you don&#8217;t need to worry about this: you can just spin up objects to implement interfaces or abstract classes, or just to tweak concrete classes, and save yourself the overhead of writing a special class definition out longhand.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2011/03/17/object-expressions-in-f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Recursive iterators in F#</title>
		<link>http://www.mindscapehq.com/blog/index.php/2011/02/28/recursive-iterators-in-f/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2011/02/28/recursive-iterators-in-f/#comments</comments>
		<pubDate>Tue, 01 Mar 2011 01:05:41 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=2810</guid>
		<description><![CDATA[C#&#8217;s iterator feature makes it very easy to produce sequences without having to build your own data structure &#8212; particularly handy for lazy sequences. However one common niggle is that if the iterator obtains a sequence of things it wants to include in its returned sequence, it has to explicitly traverse that sequence yielding them [...]]]></description>
				<content:encoded><![CDATA[<p>C#&#8217;s iterator feature makes it very easy to produce sequences without having to build your own data structure &#8212; particularly handy for lazy sequences.  However one common niggle is that if the iterator obtains a sequence of things it wants to include in its returned sequence, it has to explicitly traverse that sequence yielding them one at a time.  A place this often turns up is when the iterator calls itself recursively, for example when traversing a hierarchy.  For example, consider an iterator that gets all the files in or below a specified directory:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> IEnumerable<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span> FilesBelow<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> directory<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>var file <span style="color: #0600FF; font-weight: bold;">in</span> Directory<span style="color: #008000;">.</span><span style="color: #0000FF;">EnumerateFiles</span><span style="color: #008000;">&#40;</span>directory<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">yield</span> <span style="color: #0600FF; font-weight: bold;">return</span> file<span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
  <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>var subdir <span style="color: #0600FF; font-weight: bold;">in</span> Directory<span style="color: #008000;">.</span><span style="color: #0000FF;">EnumerateDirectories</span><span style="color: #008000;">&#40;</span>directory<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// yield return FilesBelow(subdir);  // won't compile</span>
    <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>var file <span style="color: #0600FF; font-weight: bold;">in</span> FilesBelow<span style="color: #008000;">&#40;</span>subdir<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
      <span style="color: #0600FF; font-weight: bold;">yield</span> <span style="color: #0600FF; font-weight: bold;">return</span> file<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Note the extra foreach loop over the results of the recursive call.</p>
<p>F# has something similar to iterators, which it calls sequence expressions.  A sequence expression is introduced by the term <em>seq</em>, and similar to C# it uses the term <em>yield</em> to produce values:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">seq <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">for</span> n <span style="color: #0600FF; font-weight: bold;">in</span> <span style="color: #FF0000;">1</span> <span style="color: #008000;">..</span> <span style="color: #FF0000;">10</span> <span style="color: #0600FF; font-weight: bold;">do</span> <span style="color: #0600FF; font-weight: bold;">yield</span> n <span style="color: #008000;">*</span> n <span style="color: #008000;">&#125;</span>  <span style="color: #008080; font-style: italic;">// yields 1, 4, 9 ... 81, 100</span></pre></div></div>

<p>(You can use <code>-></code> as a shorthand for <em>do yield</em> here, but I&#8217;ve spelled it out explicitly because of what&#8217;s coming next.)</p>
<p>Like a C# iterator, a F# sequence expression can call functions which return sequences and yield up the results.  We can therefore rewrite our C# directory flattening function like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let rec filesBelow directory <span style="color: #008000;">=</span>
  seq <span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">for</span> f <span style="color: #0600FF; font-weight: bold;">in</span> Directory<span style="color: #008000;">.</span><span style="color: #0000FF;">EnumerateFiles</span><span style="color: #008000;">&#40;</span>directory<span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">do</span> <span style="color: #0600FF; font-weight: bold;">yield</span> f
    <span style="color: #0600FF; font-weight: bold;">for</span> d <span style="color: #0600FF; font-weight: bold;">in</span> Directory<span style="color: #008000;">.</span><span style="color: #0000FF;">EnumerateDirectories</span><span style="color: #008000;">&#40;</span>directory<span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">do</span>
      <span style="color: #0600FF; font-weight: bold;">for</span> f <span style="color: #0600FF; font-weight: bold;">in</span> <span style="color: #008000;">&#40;</span>filesBelow d<span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">do</span>
        <span style="color: #0600FF; font-weight: bold;">yield</span> f
  <span style="color: #008000;">&#125;</span></pre></div></div>

<p>Unlike C#, however, F# sequence expressions <em>do</em> have a special keyword for yielding an entire sequence.  That keyword is <em>yield!</em>, pronounced yield-bang.  <em>yield!</em> allows us to tighten up our recursive iterator nicely:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let rec filesBelow directory <span style="color: #008000;">=</span>
  seq <span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">for</span> f <span style="color: #0600FF; font-weight: bold;">in</span> Directory<span style="color: #008000;">.</span><span style="color: #0000FF;">EnumerateFiles</span><span style="color: #008000;">&#40;</span>directory<span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">do</span> <span style="color: #0600FF; font-weight: bold;">yield</span> f
    <span style="color: #0600FF; font-weight: bold;">for</span> d <span style="color: #0600FF; font-weight: bold;">in</span> Directory<span style="color: #008000;">.</span><span style="color: #0000FF;">EnumerateDirectories</span><span style="color: #008000;">&#40;</span>directory<span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">do</span> <span style="color: #0600FF; font-weight: bold;">yield</span><span style="color: #008000;">!</span> <span style="color: #008000;">&#40;</span>filesBelow d<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#125;</span></pre></div></div>

<p>Using <em>yield!</em> on the results of the recursive call allows us to avoid the noise of the extra &#8216;for&#8217; expression.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2011/02/28/recursive-iterators-in-f/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Functions versus member methods in F#</title>
		<link>http://www.mindscapehq.com/blog/index.php/2011/02/27/functions-versus-member-methods-in-f/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2011/02/27/functions-versus-member-methods-in-f/#comments</comments>
		<pubDate>Mon, 28 Feb 2011 00:42:01 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=2802</guid>
		<description><![CDATA[F# is a hybrid object-functional language, and allows you to write code in member methods (like C# methods) or in global functions. The F# library contains several cases where a member and a global function do the same thing. For example: &#62; let l = &#91; 1; 2; 3 &#93;;; val l : int list [...]]]></description>
				<content:encoded><![CDATA[<p>F# is a hybrid object-functional language, and allows you to write code in member methods (like C# methods) or in global functions.  The F# library contains several cases where a member and a global function do the same thing.  For example:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&gt;</span> let l <span style="color: #008000;">=</span> <span style="color: #008000;">&#91;</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span> <span style="color: #FF0000;">2</span><span style="color: #008000;">;</span> <span style="color: #FF0000;">3</span> <span style="color: #008000;">&#93;</span><span style="color: #008000;">;;</span>
val l <span style="color: #008000;">:</span> <span style="color: #6666cc; font-weight: bold;">int</span> list <span style="color: #008000;">=</span> <span style="color: #008000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #008000;">;</span> <span style="color: #FF0000;">2</span><span style="color: #008000;">;</span> <span style="color: #FF0000;">3</span><span style="color: #008000;">&#93;</span>
<span style="color: #008000;">&gt;</span> l<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span><span style="color: #008000;">;;</span>
val it <span style="color: #008000;">:</span> <span style="color: #6666cc; font-weight: bold;">int</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>
<span style="color: #008000;">&gt;</span> List<span style="color: #008000;">.</span><span style="color: #0000FF;">length</span> l<span style="color: #008000;">;;</span>
val it <span style="color: #008000;">:</span> <span style="color: #6666cc; font-weight: bold;">int</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span></pre></div></div>

<p>Several other List module functions, such as head and tail, are also duplicated by properties.  It&#8217;s not just lists, either: for example, the .NET String.Length property is duplicated by the F# library String.length module function.</p>
<p>So when would you choose a member such as .Length member over a function such as List.length or String.length, or vice versa?</p>
<p>The answer, perhaps surprisingly, is that you should usually choose the function.  The reason is to do with F# type inference.</p>
<p>In F# code, you don&#8217;t usually need to specify the types of variables and parameters, because the compiler will work them out by analysing the code.  Take a look at the following code fragment:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let twiceLength a <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span> <span style="color: #008000;">*</span> List<span style="color: #008000;">.</span><span style="color: #0000FF;">length</span> a</pre></div></div>

<p>F# infers that <em>twiceLength</em> takes a list and returns an int.  We&#8217;ve not had to specify this: F# has worked it out.  How?</p>
<p>Well, when F# tries to work out the type of <em>a</em>, it looks at how <em>a</em> is used in the body of the function.  It sees that <em>a</em> is passed to the List.length function.  Now it looks at the List.length function and sees that its argument is of list type.  So, F# reasons, <em>a</em> must be of list type.  Job done!</p>
<p>But what if we wrote the function using a member?</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let twiceLength a <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span> <span style="color: #008000;">*</span> a<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span></pre></div></div>

<p>Oh no!  We get a compiler error, &#8220;Lookup on object of indeterminate type based on information prior to this program point.&#8221;  What does this mean?  It means that F# can only figure out that <em>a</em> must be something with a .Length member.  And that&#8217;s not enough to pin down the type.  List has a .Length member, String has a .Length member, ExperimentalGermanFilm has a .Length member&#8230; F# can&#8217;t tell which of these is intended, so automatic type inference fails, and we have to go back to writing it out longhand:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let twiceLength <span style="color: #008000;">&#40;</span>a <span style="color: #008000;">:</span> <span style="color: #6666cc; font-weight: bold;">String</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span> <span style="color: #008000;">*</span> a<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span>  <span style="color: #008080; font-style: italic;">// Now F# can resolve the .Length call</span></pre></div></div>

<p>In terms of the amount of code, there isn&#8217;t much to choose between the two.  And of course, if you&#8217;re working with a type that only comes with members, not helper functions, then you&#8217;ll have to go the type annotation route &#8212; not that there&#8217;s anything wrong with that.  But type inference is a bit more idiomatic where you have a choice.</p>
<p>And that, my liege, is how we know the earth to be banana shaped.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2011/02/27/functions-versus-member-methods-in-f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>First-class functions in F#, part 0</title>
		<link>http://www.mindscapehq.com/blog/index.php/2011/02/23/first-class-functions-in-f-part-0/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2011/02/23/first-class-functions-in-f-part-0/#comments</comments>
		<pubDate>Wed, 23 Feb 2011 23:31:06 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=2768</guid>
		<description><![CDATA[I wrote a while back about how F# makes it easy to work with functions, but this recent question on Stack Overflow reminded me that I hadn&#8217;t really talked about the fundamental difference between F#&#8217;s first-class functions and C#/VB&#8217;s delegates. In C# and Visual Basic, there are delegate types for all kinds of function signatures, [...]]]></description>
				<content:encoded><![CDATA[<p>I wrote a while back about how <a href="http://www.mindscapehq.com/blog/index.php/2010/10/10/f-and-first-class-functions-part-1-the-composition-operator/">F# makes it easy to work with functions</a>, but this <a href="http://stackoverflow.com/questions/4965576/c-why-cant-var-be-assigned-to-an-anonymous-method">recent question on Stack Overflow</a> reminded me that I hadn&#8217;t really talked about the fundamental difference between F#&#8217;s first-class functions and C#/VB&#8217;s delegates.  In C# and Visual Basic, there are delegate types for all kinds of function signatures, but there&#8217;s no canonical function type.  Whereas in F#, function types are part of the language.</p>
<p>Consider the following line of C#:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var isReticulated <span style="color: #008000;">=</span> <span style="color: #6666cc; font-weight: bold;">delegate</span><span style="color: #008000;">&#40;</span>Spline s<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> s<span style="color: #008000;">.</span><span style="color: #0000FF;">IsReticulated</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span></pre></div></div>

<p>As the Stack Overflow poster discovered, this doesn&#8217;t compile.  Why not?  Because although the right hand side is clearly a function from Spline to bool, <em>C# doesn&#8217;t recognise that as a type</em>.  C# only recognises specific delegate types such as <code>Func&lt;Spline, bool&gt;</code>, <code>Predicate&lt;Spline&gt;</code> or <code>Converter&lt;Spline, bool&gt;</code>.  So you have to pick one of these and spell it out:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Predicate<span style="color: #008000;">&lt;</span>Spline<span style="color: #008000;">&gt;</span> isReticulated <span style="color: #008000;">=</span> <span style="color: #6666cc; font-weight: bold;">delegate</span><span style="color: #008000;">&#40;</span>Spline s<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> s<span style="color: #008000;">.</span><span style="color: #0000FF;">IsReticulated</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And woe betide you if you have to deal with APIs that have made different choices, because there&#8217;s no conversion between &#8216;compatible&#8217; delegate types:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> Predicate<span style="color: #008000;">&lt;</span>Person<span style="color: #008000;">&gt;</span> GetFilter<span style="color: #008000;">&#40;</span>FilterSpecification spec<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #008000;">...</span> <span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> IEnumerable<span style="color: #008000;">&lt;</span>Person<span style="color: #008000;">&gt;</span> GetFilteredPeople<span style="color: #008000;">&#40;</span>FilterSpecification spec<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  var filter <span style="color: #008000;">=</span> GetFilter<span style="color: #008000;">&#40;</span>spec<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF; font-weight: bold;">return</span> _people<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Where</span><span style="color: #008000;">&#40;</span>filter<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// compiler error</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The Where method demands a <code>Func&lt;T, bool&gt;</code>, so if all you have is a <code>Predicate&lt;T&gt;</code> then you&#8217;re stuffed, even though they&#8217;re both functions from T to bool!  Instead you have to write a guffy little adapter:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">return</span> _people<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Where</span><span style="color: #008000;">&#40;</span>p <span style="color: #008000;">=&gt;</span> filter<span style="color: #008000;">&#40;</span>p<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// everybody loves code noise</span></pre></div></div>

<p>Contrast this with F#, in which functions do have a type:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let isReticulated <span style="color: #008000;">=</span> fun <span style="color: #008000;">&#40;</span>s <span style="color: #008000;">:</span> Spline<span style="color: #008000;">&#41;</span> <span style="color: #008000;">-&gt;</span> s<span style="color: #008000;">.</span><span style="color: #0000FF;">IsReticulated</span></pre></div></div>

<p>The compiler figures out the type as <code>Spline -> bool</code>.  Which means you can pass this function to anything that expects a function from Spline to bool.  You don&#8217;t need to worry about the difference between Funcs, Predicates, Converters and goodness knows what else: instead, function types are standardised at the language level.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">let reticulatedSplines <span style="color: #008000;">=</span> List<span style="color: #008000;">.</span><span style="color: #0000FF;">filter</span> isReticulated splines  <span style="color: #008080; font-style: italic;">// List.filter takes a 'T -&gt; bool</span>
let antifilter predicate list <span style="color: #008000;">=</span> List<span style="color: #008000;">.</span><span style="color: #0000FF;">filter</span> <span style="color: #008000;">&#40;</span>predicate <span style="color: #008000;">&gt;&gt;</span> not<span style="color: #008000;">&#41;</span> list  <span style="color: #008080; font-style: italic;">// Compiler infers type of predicate as 'T -&gt; bool</span>
let unreticulatedSplines <span style="color: #008000;">=</span> antifilter isReticulated splines  <span style="color: #008080; font-style: italic;">// so isReticulated is compatible with antifilter</span></pre></div></div>

<p>Any function with a function argument can work with <em>any</em> function with the right signature &#8212; not just ones that happen to have been packaged up into the right delegate type.</p>
<p>And that, at bottom, is why functions are first class in F#, and not in C# or Visual Basic.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2011/02/23/first-class-functions-in-f-part-0/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: basic (Requested URI is rejected)
Database Caching 9/22 queries in 0.020 seconds using disk: basic

 Served from: www.mindscapehq.com @ 2013-06-19 20:20:21 by W3 Total Cache -->