<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>LukeH's WebLog</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/lukeh/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/lukeh/feed.xml</link>
    <description />
    <lastBuildDate>Wed, 17 Apr 2019 03:24:38 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Benoit Mandelbrot</title>
      <link>https://docs.microsoft.com/archive/blogs/lukeh/benoit-mandelbrot</link>
      <pubDate>Sat, 16 Oct 2010 14:20:00 GMT</pubDate>
      <dc:creator><![CDATA[Luke Hoban [MS]]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/lukeh/2010/10/16/benoit-mandelbrot/</guid>
      <description><![CDATA[I just read that earlier today, Beno&icirc;t Mandelbrot passed away.&nbsp; Mandelbrot&rsquo;s most...]]></description>
      <content:encoded><![CDATA[<p>I just read that earlier today, Beno&icirc;t Mandelbrot <a href="https://www.nytimes.com/2010/10/17/us/17mandelbrot.html?_r=2">passed away</a>.&nbsp; <a href="https://en.wikipedia.org/wiki/Beno%C3%AEt_Mandelbrot">Mandelbrot&rsquo;s</a> most famous discovery, the <a href="https://en.wikipedia.org/wiki/Mandelbrot_set">Mandelbrot fractal</a>, played an important early role in my interest in both programming and mathematics, and I&rsquo;ve revisited Mandelbrot fractals many times as programming samples for new languages or frameworks I&rsquo;ve looked at.&nbsp; I was lucky to have an opportunity to hear Mandelbrot speak in person a few years ago when he stopped by the Microsoft campus on a book tour for his book <a href="https://www.amazon.com/Misbehavior-Markets-Fractal-Financial-Turbulence/dp/0465043577/ref=sr_1_1?ie=UTF8&amp;qid=1287262524&amp;sr=8-1">The Misbehaviour of Markets: A Fractal View of Financial Turbulence</a>.&nbsp;</p>
<p>In honor of Mandelbrot, here are two very simple takes on the Mandelbrot fractal that I&rsquo;ve written in the last couple years.</p>
<h2>Mandelbrot in the F# Interactive</h2>
<p>One of the first pieces of F# code I wrote is below.&nbsp; I blogged about this <a href="https://blogs.msdn.com/b/lukeh/archive/2007/11/14/f.aspx">here</a>.</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/37/86/metablogapi/8741.image_2CC714ED.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-37-86-metablogapi/8741.image_5F00_2CC714ED.png"><img style="display: inline; border-width: 0px;" title="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/37/86/metablogapi/0246.image_thumb_3954C209.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-37-86-metablogapi/0246.image_5F00_thumb_5F00_3954C209.png" alt="image" width="343" height="604" border="0" /></a>&nbsp;&nbsp;</p>
<h2>Mandelbrot in 175 characters of Javascript</h2>
<p>Inspired by the <a href="https://js1k.com/home">js1k.com</a> competition earlier this year, I adapted Ken Perlin&rsquo;s very cool <a href="https://mrl.nyu.edu/~perlin/">C program</a> to Javascript as a 175 character program for rendering a Mandelbrot fractal in any browser.&nbsp; Couldn&rsquo;t quite get it to fit in a single tweet though (rule #6 of the js1k challenge).</p>
<pre>y=-16;s="&lt;pre&gt;";while(s+='\n',y++&lt;15)for(x=0;x++&lt;84;s+=(" 
.:-;!/&gt;)|&amp;IH%*#"[k&amp;15]))for(i=k=r=0;j=r*r-i*i-2+x/25,i=2*r
*i+y/10,j*j+i*i&lt;11&amp;&amp;k++&lt;111;r=j);document.body.innerHTML=s</pre>
<p>&nbsp;<a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/37/86/metablogapi/3858.clip_image001_21AC4CB9.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-37-86-metablogapi/3858.clip_5F00_image001_5F00_21AC4CB9.png"><img style="display: inline; border: 0px;" title="clip_image001" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/37/86/metablogapi/7266.clip_image001_thumb_05BB17C1.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-37-86-metablogapi/7266.clip_5F00_image001_5F00_thumb_5F00_05BB17C1.png" alt="clip_image001" width="327" height="230" border="0" /></a></p>
<p>Check it out <a href="https://lukeh-blog.azurewebsites.net/mandeltext.html">here</a> for the full page source.</p>
<p>[UPDATE: &nbsp;And <a href="https://lukeh-blog.azurewebsites.net/mandelcanvas.html">here</a>'s a slightly more fully featured implementation, using Javascript and HTML5 canvas. ]&nbsp;</p>]]></content:encoded>
    </item>
    <item>
      <title>Twitter OAuth in F#</title>
      <link>https://docs.microsoft.com/archive/blogs/lukeh/twitter-oauth-in-f</link>
      <pubDate>Sun, 05 Sep 2010 17:30:37 GMT</pubDate>
      <dc:creator><![CDATA[Luke Hoban [MS]]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/lukeh/2010/09/05/twitter-oauth-in-f/</guid>
      <description><![CDATA[I have a few F# demos which use the Twitter APIs as simple examples of accessing online data...]]></description>
      <content:encoded><![CDATA[<p>I have a few F# demos which use the Twitter APIs as simple examples of accessing online data interactively and working with it in F#.&#160;&#160;&#160; Recently, Twitter moved to require OAuth for accessing Twitter APIs on behalf of a user.&#160; Below is the F# code I wrote to integrate OAuth, which should work for any other F# Twitter scripts and apps.</p>  <h5>OAuth Implementation</h5>  <blockquote>   <pre class="code"><span style="color: blue">open </span>System
<span style="color: blue">open </span>System.IO
<span style="color: blue">open </span>System.Net
<span style="color: blue">open </span>System.Security.Cryptography
<span style="color: blue">open </span>System.Text

<span style="color: green">// Twitter OAuth Constants
</span><span style="color: blue">let </span>consumerKey : string = failwith <span style="color: maroon">&quot;Must provide the consumerKey for an app registered at https://dev.twitter.com/apps/new&quot;
</span><span style="color: blue">let </span>consumerSecret : string = failwith <span style="color: maroon">&quot;Must provide the consumerSecret for an app registered at https://dev.twitter.com/apps/new&quot;
</span><span style="color: blue">let </span>requestTokenURI = <span style="color: maroon">&quot;https://api.twitter.com/oauth/request_token&quot;
</span><span style="color: blue">let </span>accessTokenURI = <span style="color: maroon">&quot;https://api.twitter.com/oauth/access_token&quot;
</span><span style="color: blue">let </span>authorizeURI = <span style="color: maroon">&quot;https://api.twitter.com/oauth/authorize&quot;


</span><span style="color: green">// Utilities
</span><span style="color: blue">let </span>unreservedChars = <span style="color: maroon">&quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~&quot;</span>;
<span style="color: blue">let </span>urlEncode str = 
    String.init (String.length str) (<span style="color: blue">fun </span>i <span style="color: blue">-&gt; 
        let </span>symbol = str.[i]
        <span style="color: blue">if </span>unreservedChars.IndexOf(symbol) = -1 <span style="color: blue">then
            </span><span style="color: maroon">&quot;%&quot; </span>+ String.Format(<span style="color: maroon">&quot;{0:X2}&quot;</span>, int symbol)
        <span style="color: blue">else
            </span>string symbol)


<span style="color: green">// Core Algorithms
</span><span style="color: blue">let </span>hmacsha1 signingKey str = 
    <span style="color: blue">let </span>converter = <span style="color: blue">new </span>HMACSHA1(Encoding.ASCII.GetBytes(signingKey : string))
    <span style="color: blue">let </span>inBytes = Encoding.ASCII.GetBytes(str : string)
    <span style="color: blue">let </span>outBytes = converter.ComputeHash(inBytes)
    Convert.ToBase64String(outBytes)

<span style="color: blue">let </span>compositeSigningKey consumerSecret tokenSecret = 
    urlEncode(consumerSecret) + <span style="color: maroon">&quot;&amp;&quot; </span>+ urlEncode(tokenSecret)

<span style="color: blue">let </span>baseString httpMethod baseUri queryParameters = 
    httpMethod + <span style="color: maroon">&quot;&amp;&quot; </span>+ 
    urlEncode(baseUri) + <span style="color: maroon">&quot;&amp;&quot; </span>+
    (queryParameters 
     |&gt; Seq.sortBy (<span style="color: blue">fun </span>(k,v) <span style="color: blue">-&gt; </span>k)
     |&gt; Seq.map (<span style="color: blue">fun </span>(k,v) <span style="color: blue">-&gt; </span>urlEncode(k)+<span style="color: maroon">&quot;%3D&quot;</span>+urlEncode(v))
     |&gt; String.concat <span style="color: maroon">&quot;%26&quot;</span>) 

<span style="color: blue">let </span>createAuthorizeHeader queryParameters = 
    <span style="color: blue">let </span>headerValue = 
        <span style="color: maroon">&quot;OAuth &quot; </span>+ 
        (queryParameters
         |&gt; Seq.map (<span style="color: blue">fun </span>(k,v) <span style="color: blue">-&gt; </span>urlEncode(k)+<span style="color: maroon">&quot;\x3D\&quot;&quot;</span>+urlEncode(v)+<span style="color: maroon">&quot;\&quot;&quot;</span>)
         |&gt; String.concat <span style="color: maroon">&quot;,&quot;</span>)
    headerValue

<span style="color: blue">let </span>currentUnixTime() = floor (DateTime.UtcNow - DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds


<span style="color: green">/// Request a token from Twitter and return:
///  oauth_token, oauth_token_secret, oauth_callback_confirmed
</span><span style="color: blue">let </span>requestToken() = 
    <span style="color: blue">let </span>signingKey = compositeSigningKey consumerSecret <span style="color: maroon">&quot;&quot;

    </span><span style="color: blue">let </span>queryParameters = 
        [<span style="color: maroon">&quot;oauth_callback&quot;</span>, <span style="color: maroon">&quot;oob&quot;</span>;
         <span style="color: maroon">&quot;oauth_consumer_key&quot;</span>, consumerKey;
         <span style="color: maroon">&quot;oauth_nonce&quot;</span>, System.Guid.NewGuid().ToString().Substring(24);
         <span style="color: maroon">&quot;oauth_signature_method&quot;</span>, <span style="color: maroon">&quot;HMAC-SHA1&quot;</span>;
         <span style="color: maroon">&quot;oauth_timestamp&quot;</span>, currentUnixTime().ToString();
         <span style="color: maroon">&quot;oauth_version&quot;</span>, <span style="color: maroon">&quot;1.0&quot;</span>]

    <span style="color: blue">let </span>signingString = baseString <span style="color: maroon">&quot;POST&quot; </span>requestTokenURI queryParameters
    <span style="color: blue">let </span>oauth_signature = hmacsha1 signingKey signingString

    <span style="color: blue">let </span>realQueryParameters = (<span style="color: maroon">&quot;oauth_signature&quot;</span>, oauth_signature)::queryParameters

    <span style="color: blue">let </span>req = WebRequest.Create(requestTokenURI, Method=<span style="color: maroon">&quot;POST&quot;</span>)
    <span style="color: blue">let </span>headerValue = createAuthorizeHeader realQueryParameters
    req.Headers.Add(HttpRequestHeader.Authorization, headerValue)
    
    <span style="color: blue">let </span>resp = req.GetResponse()
    <span style="color: blue">let </span>stream = resp.GetResponseStream()
    <span style="color: blue">let </span>txt = (<span style="color: blue">new </span>StreamReader(stream)).ReadToEnd()
    
    <span style="color: blue">let </span>parts = txt.Split(<span style="color: maroon">'&amp;'</span>)
    (parts.[0].Split(<span style="color: maroon">'='</span>).[1],
     parts.[1].Split(<span style="color: maroon">'='</span>).[1],
     parts.[2].Split(<span style="color: maroon">'='</span>).[1] = <span style="color: maroon">&quot;true&quot;</span>)

<span style="color: green">/// Get an access token from Twitter and returns:
///   oauth_token, oauth_token_secret
</span><span style="color: blue">let </span>accessToken token tokenSecret verifier =
    <span style="color: blue">let </span>signingKey = compositeSigningKey consumerSecret tokenSecret

    <span style="color: blue">let </span>queryParameters = 
        [<span style="color: maroon">&quot;oauth_consumer_key&quot;</span>, consumerKey;
         <span style="color: maroon">&quot;oauth_nonce&quot;</span>, System.Guid.NewGuid().ToString().Substring(24);
         <span style="color: maroon">&quot;oauth_signature_method&quot;</span>, <span style="color: maroon">&quot;HMAC-SHA1&quot;</span>;
         <span style="color: maroon">&quot;oauth_token&quot;</span>, token;
         <span style="color: maroon">&quot;oauth_timestamp&quot;</span>, currentUnixTime().ToString();
         <span style="color: maroon">&quot;oauth_verifier&quot;</span>, verifier;
         <span style="color: maroon">&quot;oauth_version&quot;</span>, <span style="color: maroon">&quot;1.0&quot;</span>]

    <span style="color: blue">let </span>signingString = baseString <span style="color: maroon">&quot;POST&quot; </span>accessTokenURI queryParameters
    <span style="color: blue">let </span>oauth_signature = hmacsha1 signingKey signingString
    
    <span style="color: blue">let </span>realQueryParameters = (<span style="color: maroon">&quot;oauth_signature&quot;</span>, oauth_signature)::queryParameters
    
    <span style="color: blue">let </span>req = WebRequest.Create(accessTokenURI, Method=<span style="color: maroon">&quot;POST&quot;</span>)
    <span style="color: blue">let </span>headerValue = createAuthorizeHeader realQueryParameters
    req.Headers.Add(HttpRequestHeader.Authorization, headerValue)
    
    <span style="color: blue">let </span>resp = req.GetResponse()
    <span style="color: blue">let </span>stream = resp.GetResponseStream()
    <span style="color: blue">let </span>txt = (<span style="color: blue">new </span>StreamReader(stream)).ReadToEnd()
    
    <span style="color: blue">let </span>parts = txt.Split(<span style="color: maroon">'&amp;'</span>)
    (parts.[0].Split(<span style="color: maroon">'='</span>).[1],
     parts.[1].Split(<span style="color: maroon">'='</span>).[1])

<span style="color: green">/// Compute the 'Authorization' header for the given request data
</span><span style="color: blue">let </span>authHeaderAfterAuthenticated url httpMethod token tokenSecret queryParams = 
    <span style="color: blue">let </span>signingKey = compositeSigningKey consumerSecret tokenSecret

    <span style="color: blue">let </span>queryParameters = 
            [<span style="color: maroon">&quot;oauth_consumer_key&quot;</span>, consumerKey;
             <span style="color: maroon">&quot;oauth_nonce&quot;</span>, System.Guid.NewGuid().ToString().Substring(24);
             <span style="color: maroon">&quot;oauth_signature_method&quot;</span>, <span style="color: maroon">&quot;HMAC-SHA1&quot;</span>;
             <span style="color: maroon">&quot;oauth_token&quot;</span>, token;
             <span style="color: maroon">&quot;oauth_timestamp&quot;</span>, currentUnixTime().ToString();
             <span style="color: maroon">&quot;oauth_version&quot;</span>, <span style="color: maroon">&quot;1.0&quot;</span>]

    <span style="color: blue">let </span>signingQueryParameters = 
        List.append queryParameters queryParams

    <span style="color: blue">let </span>signingString = baseString httpMethod url signingQueryParameters
    <span style="color: blue">let </span>oauth_signature = hmacsha1 signingKey signingString
    <span style="color: blue">let </span>realQueryParameters = (<span style="color: maroon">&quot;oauth_signature&quot;</span>, oauth_signature)::queryParameters
    <span style="color: blue">let </span>headerValue = createAuthorizeHeader realQueryParameters
    headerValue

<span style="color: green">/// Add an Authorization header to an existing WebRequest 
</span><span style="color: blue">let </span>addAuthHeaderForUser (webRequest : WebRequest) token tokenSecret queryParams = 
    <span style="color: blue">let </span>url = webRequest.RequestUri.ToString()
    <span style="color: blue">let </span>httpMethod = webRequest.Method
    <span style="color: blue">let </span>header = authHeaderAfterAuthenticated url httpMethod token tokenSecret queryParams
    webRequest.Headers.Add(HttpRequestHeader.Authorization, header)

<span style="color: blue">type </span>System.Net.WebRequest <span style="color: blue">with
    </span><span style="color: green">/// Add an Authorization header to the WebRequest for the provided user authorization tokens and query parameters
    </span><span style="color: blue">member </span>this.AddOAuthHeader(userToken, userTokenSecret, queryParams) =
        addAuthHeaderForUser this userToken userTokenSecret queryParams




<span style="color: blue">let </span>testing() =   

    <span style="color: green">// Compute URL to send user to to allow our app to connect with their credentials,
    // then open the browser to have them accept
    </span><span style="color: blue">let </span>oauth_token'', oauth_token_secret'', oauth_callback_confirmed = requestToken()
    <span style="color: blue">let </span>url = authorizeURI + <span style="color: maroon">&quot;?oauth_token=&quot; </span>+ oauth_token''
    System.Diagnostics.Process.Start(<span style="color: maroon">&quot;iexplore.exe&quot;</span>, url)
    
    <span style="color: green">// *******NOTE********:
    // Get the 7 digit number from the web page, pass it to the function below to get oauth_token
    // Sample result if things go okay:
    //    val oauth_token_secret' : string = &quot;lbll17CpNUlSt0FbfMKyfrzBwyHUrRrY8Ge2rEhs&quot;
    //    val oauth_token' : string = &quot;17033946-8vqDO7foX0TUNpqNg9MyJpO3Qui3nunkZPixxLs&quot;
    </span><span style="color: blue">let </span>oauth_token, oauth_token_secret = accessToken oauth_token'' oauth_token_secret'' (<font color="#800000">&quot;1579754&quot;</font>)


    <span style="color: green">// Test 1:
    </span><span style="color: blue">let </span>streamSampleUrl2 = <span style="color: maroon">&quot;https://api.twitter.com/1/statuses/home_timeline.xml&quot;
    </span><span style="color: blue">let </span>req = WebRequest.Create(streamSampleUrl2) 
    req.AddOAuthHeader(oauth_token, oauth_token_secret, [])
    <span style="color: blue">let </span>resp = req.GetResponse()
    <span style="color: blue">let </span>strm = resp.GetResponseStream()
    <span style="color: blue">let </span>text = (<span style="color: blue">new </span>StreamReader(strm)).ReadToEnd()
    text

    <span style="color: green">// Test 2:
    <font color="#000000">System.Net.ServicePointManager.Expect100Continue &lt;-</font> <span style="color: blue">false</span><br />    </span><span style="color: blue">let </span>statusUrl = <span style="color: maroon">&quot;https://twitter.com/statuses/update.xml&quot;
    </span><span style="color: blue">let </span>request = WebRequest.Create (statusUrl, Method=<span style="color: maroon">&quot;POST&quot;</span>)
    <span style="color: blue">let </span>tweet =  urlEncode(<span style="color: maroon">&quot;Hello!&quot;</span>)
    request.AddOAuthHeader(oauth_token,oauth_token_secret,[<span style="color: maroon">&quot;status&quot;</span>,tweet])
    <span style="color: blue">let </span>bodyStream = request.GetRequestStream()
    <span style="color: blue">let </span>bodyWriter = <span style="color: blue">new </span>StreamWriter(bodyStream)
    bodyWriter.Write(<span style="color: maroon">&quot;status=&quot; </span>+ tweet)
    bodyWriter.Close()
    <span style="color: blue">let </span>resp = request.GetResponse()
    <span style="color: blue">let </span>strm = resp.GetResponseStream()
    <span style="color: blue">let </span>text = (<span style="color: blue">new </span>StreamReader(strm)).ReadToEnd()
    text</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>]]></content:encoded>
    </item>
    <item>
      <title>F# Scaling from Explorative to .NET Component - F# Talk @ TechEd 2010</title>
      <link>https://docs.microsoft.com/archive/blogs/lukeh/f-scaling-from-explorative-to-net-component-f-talk-teched-2010</link>
      <pubDate>Sun, 13 Jun 2010 17:57:00 GMT</pubDate>
      <dc:creator><![CDATA[Luke Hoban [MS]]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/lukeh/2010/06/13/f-scaling-from-explorative-to-net-component-f-talk-teched-2010/</guid>
      <description><![CDATA[Last Thursday I gave an F# talk at TechEd New Orleans titled "F# in Visual Studio 2010".&nbsp; The...]]></description>
      <content:encoded><![CDATA[<p>Last Thursday I gave an F# talk at TechEd New Orleans titled "F# in Visual Studio 2010".&nbsp; The talk aimed to highlight a few ideas:</p>
<ul>
<li>F# enables exciting new developer scenarios in Visual Studio (explorative bottom-up programming in the F# Interactive) </li>
<li>F# can leverage many/most of the powerful developer tools in Visual Studio (projects, debugging, editing, help integration, etc.) and .NET (produce and consume vanilla .NET APIs) </li>
<li>F# has unique strengths in key target domains and extends the .NET platform to these audiences </li>
<li>F# scales smoothly from explorative to .NET component development (start with ideas and iteratively and smoothly add structure as methods, types and projects)</li>
</ul>
<p>The <a href="https://www.msteched.com/2010/NorthAmerica/DEV307">video of the talk</a> is available now on TechEd Online and here is the demo code below for those interested in taking a look.&nbsp; </p>
<p><a href="https://www.box.net/shared/5god6k0u0o" title="TechEd2010Demos.zip"><img height="24" width="24" src="https://www.box.net/thumbs/24x24/default_file.gif" align="absMiddle" alt="File icon" border="0" />TechEd2010Demos.zip</a></p>
<p>Those who read my blog may recognize a number of the examples as things I've posted about <a href="https://blogs.msdn.com/b/lukeh/archive/2009/06/26/f-in-silverlight.aspx">in</a> <a href="https://blogs.msdn.com/b/lukeh/archive/2009/06/26/icfp-programming-contest-2009.aspx">the</a> <a href="https://blogs.msdn.com/b/lukeh/archive/2008/05/05/huffman-coding-with-f.aspx">past</a>.&nbsp;&nbsp; The F# Silverlight apps used in the demos are also available in those previous posts.</p>
<p>There was one theme that seemed to resonate especially well - here's a few more thoughts on the idea of scaling from explorative to component building in F# from the perspective of using the "tab" refactoring in F#.</p>
<h3>"tab" as Extract Method (or, more generally, Encapsulate)</h3>
<p>Indentation is meaningful in F#, and is used to indicate nesting.&nbsp; This, along with type inference and a strong uniformity of syntax at different levels of nesting, enables a simple but really fundamental shift to how you can think about encapsulation in F#.&nbsp; </p>
<p>An example. I start by solving a problem by writing code directly at the top level.&nbsp; I don't know what shape the solution has to take yet, but I leverage the F# Interactive to prototype and explore the solution.</p>
<p>&nbsp;</p>
<pre class="code"><span style="color: blue">let </span>url = <span style="color: maroon">"https://www.yahoo.com"
</span><span style="color: blue">let </span>req    = WebRequest.Create(Uri(url))
<span style="color: blue">let </span>stream = req.GetResponse().GetResponseStream()
<span style="color: blue">let </span>reader = <span style="color: blue">new </span>StreamReader(stream)
<span style="color: blue">let </span>html   = reader.ReadToEnd()

html.Length</pre>
<p>Notice that because we're in the F# Interactive, we tend to have some sample data we want to experiment with bound in our environment - like "url" above.</p>
<p>Once we establish that this code does what we want - we can "give it a name" - using a simple and local set of changes:</p>
<pre class="code"><span style="color: blue">let </span>url = <span style="color: maroon">"https://www.yahoo.com"

</span><span style="color: blue">let </span>http url = 
    <span style="color: blue">let </span>req    = WebRequest.Create(Uri(url))
    <span style="color: blue">let </span>stream = req.GetResponse().GetResponseStream()
    <span style="color: blue">let </span>reader = <span style="color: blue">new </span>StreamReader(stream)
    <span style="color: blue">let </span>html   = reader.ReadToEnd()
    html

<span style="color: blue">let </span>html = http url
html.Length
</pre>
<p><a href="https://11011.net/software/vspaste"></a></p>
<p>We just hit "tab", and then wrote out the signature for the new function.&nbsp; Note that we were able to "parameterize over" any of the names used in this piece of code that we wanted to be variable in our abstraction.&nbsp; So in this case, we parameterize over "url".&nbsp; Any later dependencies on the results of the original code can be left intact by re-binding the name "html" to a call to the new function - thereby making this a truly local code change. </p>
<p>Notice that a key to this was the uniformity of "let" between the top level and the function body scope.&nbsp; </p>
<p>Later in my coding I may end up with something like this:</p>
<pre class="code"><span style="color: blue">let </span>username = <span style="color: maroon">"abc"
</span><span style="color: blue">let </span>password = <span style="color: maroon">"def"
    
</span><span style="color: blue">let </span>http url = 
    <span style="color: blue">let </span>credentials = NetworkCredential(username, password)
    <span style="color: blue">let </span>req    = WebRequest.Create(Uri(url), Credentials=credentials)
    <span style="color: blue">let </span>stream = req.GetResponse().GetResponseStream()
    <span style="color: blue">let </span>reader = <span style="color: blue">new </span>StreamReader(stream)
    <span style="color: blue">let </span>html   = reader.ReadToEnd()
    html
    
<span style="color: blue">let </span>homeTimeline() = http <span style="color: maroon">"https://api.twitter.com/statuses/home_timeline.xml"
</span><span style="color: blue">let </span>publicTimeline() = http <span style="color: maroon">"https://api.twitter.com/statuses/public_timeline.xml"
</span><span style="color: blue">let </span>userTimeline() = http <span style="color: maroon">"https://api.twitter.com/statuses/user_timeline.xml"

</span></pre>
<p><a href="https://11011.net/software/vspaste"></a></p>
<p>At this point, I have some interesting functionality - and may want to introduce a true component to encapsulate the implementation and expose an intentionally designed API.&nbsp; OO is an excellent and proven tool for component design, and is a key part of F# programming.&nbsp; It is also very easy to smoothly transition from simple top level coding into F# component design with OO.&nbsp; And again - it's mostly just about "tab".</p>
<pre class="code"><span style="color: blue">let </span>username = <span style="color: maroon">"abc"
</span><span style="color: blue">let </span>password = <span style="color: maroon">"def"

</span><span style="color: blue">type </span>Twitter(username, password) =     
    <span style="color: blue">let </span>http url = 
        <span style="color: blue">let </span>credentials = NetworkCredential(username, password)
        <span style="color: blue">let </span>req    = WebRequest.Create(Uri(url), Credentials=credentials)
        <span style="color: blue">let </span>stream = req.GetResponse().GetResponseStream()
        <span style="color: blue">let </span>reader = <span style="color: blue">new </span>StreamReader(stream)
        <span style="color: blue">let </span>html   = reader.ReadToEnd()
        html
    
    <span style="color: blue">let </span>homeTimeline() = http <span style="color: maroon">"https://api.twitter.com/statuses/home_timeline.xml"
    </span><span style="color: blue">let </span>userTimeline() = http <span style="color: maroon">"https://api.twitter.com/statuses/user_timeline.xml"
    </span><span style="color: blue">let </span>publicTimeline() = http <span style="color: maroon">"https://api.twitter.com/statuses/public_timeline.xml"
    
    </span><span style="color: blue">member </span>this.HomeTimeline() = homeTimeline()
    <span style="color: blue">member </span>this.UserTimeline() = userTimeline()
    <span style="color: blue">member </span>this.PublicTimeline() = publicTimeline()

<span style="color: blue">let </span>twitter = <span style="color: blue">new </span>Twitter(username, password)
<span style="color: blue">let </span>homeTimeline = twitter.HomeTimeline()
<span style="color: blue">let </span>userTimeline = twitter.UserTimeline()
<span style="color: blue">let </span>publicTimeline = twitter.PublicTimeline()</pre>
<p><a href="https://11011.net/software/vspaste"></a></p>
<p>Notice how similar this transition was to the change we needed to give the "http" function a name.&nbsp; In this case, we just tab in all the code except the things we want to parameterize over, give the signature of the type and it's constructor (again, the things we want to parameterize over), and then define the API we want to expose from the functionality as "member" definitions.</p>
<p>So we've now introduced a true .NET class with the API we want.&nbsp; The last step is to transition from the explorative environment to a component.&nbsp; We can just take the code above - strip off the sample data that was just there to experiment in the F# Interactive - and compile into a .NET assembly:</p>
<pre class="code"><span style="color: blue">namespace </span>TwitterAPI

<span style="color: blue">open </span>System
<span style="color: blue">open </span>System.Net
<span style="color: blue">open </span>System.IO

<span style="color: blue">type </span>Twitter(username : string, password : string) =     
    <span style="color: blue">let </span>http url = 
        <span style="color: blue">let </span>credentials = NetworkCredential(username, password)
        <span style="color: blue">let </span>req    = WebRequest.Create(Uri(url), Credentials=credentials)
        <span style="color: blue">let </span>stream = req.GetResponse().GetResponseStream()
        <span style="color: blue">let </span>reader = <span style="color: blue">new </span>StreamReader(stream)
        <span style="color: blue">let </span>html   = reader.ReadToEnd()
        html
    
    <span style="color: blue">let </span>homeTimeline() = http <span style="color: maroon">"https://api.twitter.com/statuses/home_timeline.xml"
    </span><span style="color: blue">let </span>userTimeline() = http <span style="color: maroon">"https://api.twitter.com/statuses/user_timeline.xml"
    </span><span style="color: blue">let </span>publicTimeline() = http <span style="color: maroon">"https://api.twitter.com/statuses/public_timeline.xml"
    
    </span><span style="color: blue">member </span>this.HomeTimeline() = homeTimeline()
    <span style="color: blue">member </span>this.UserTimeline() = userTimeline()
    <span style="color: blue">member </span>this.PublicTimeline() = publicTimeline()</pre>
<pre class="code"></pre>
<p><a href="https://11011.net/software/vspaste"></a></p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/37/86/metablogapi/7268.image_2.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-37-86-metablogapi/7268.image_5F00_2.png"><img height="388" width="516" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/37/86/metablogapi/8764.image_thumb.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-37-86-metablogapi/8764.image_5F00_thumb.png" alt="image" border="0" title="image" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" /></a> </p>
<p>And then we can use this from C# (or VB, or any other .NET language):</p>
<pre class="code"><span style="color: blue">using </span>System;
<span style="color: blue">using </span>TwitterAPI;

<span style="color: blue">class </span><span style="color: #2b91af">Program
</span>{
    <span style="color: blue">static void </span>Main(<span style="color: blue">string</span>[] args)
    {
        <span style="color: #2b91af">Twitter </span>twitter = <span style="color: blue">new </span><span style="color: #2b91af">Twitter</span>(<span style="color: #a31515">"abc"</span>, <span style="color: #a31515">"def"</span>);
        <span style="color: blue">string </span>homeTimeline = twitter.HomeTimeline();
        <span style="color: #2b91af">Console</span>.WriteLine(homeTimeline);
    }
}

</pre>
<p><a href="https://11011.net/software/vspaste"></a></p>
<h3>Summary</h3>
<p>The TechEd talk covered a number of interesting aspects of using F# in Visual Studio - tools, core syntax, some examples of current commercial users, and the physical structure of F# projects used in client applications.&nbsp; But the theme of scaling from explorative programming to .NET component is one that I find particularly powerful, and which is a really unique strength of the F# language.</p>
<p>&nbsp;</p>
<p><a href="https://www.box.net/shared/5god6k0u0o" title="TechEd2010Demos.zip"><img height="24" width="24" src="https://www.box.net/thumbs/24x24/default_file.gif" align="absMiddle" alt="File icon" border="0" />TechEd2010Demos.zip</a></p>]]></content:encoded>
    </item>
    <item>
      <title>F# for Parallel and Asynchronous Programming - PDC 2009</title>
      <link>https://docs.microsoft.com/archive/blogs/lukeh/f-for-parallel-and-asynchronous-programming-pdc-2009</link>
      <pubDate>Sun, 31 Jan 2010 23:43:00 GMT</pubDate>
      <dc:creator><![CDATA[Luke Hoban [MS]]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/lukeh/2010/01/31/f-for-parallel-and-asynchronous-programming-pdc-2009/</guid>
      <description><![CDATA[Last November at PDC 2009 in Los Angeles I gave a talk on F# for Parallel and Asynchronous...]]></description>
      <content:encoded><![CDATA[<h2><a href="https://microsoftpdc.com/Sessions/FT20" mce_href="https://microsoftpdc.com/Sessions/FT20"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" align="right" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/lukeh/WindowsLiveWriter/FforParallelandAsynchronousProgrammingPD_EBAD/image_3.png" original-url="https://blogs.msdn.com/blogfiles/lukeh/WindowsLiveWriter/FforParallelandAsynchronousProgrammingPD_EBAD/image_3.png" width="240" height="135" mce_src="https://blogs.msdn.com/blogfiles/lukeh/WindowsLiveWriter/FforParallelandAsynchronousProgrammingPD_EBAD/image_3.png"></a></h2> <p>Last November at PDC 2009 in Los Angeles I gave a talk on F# for Parallel and Asynchronous Programming.&nbsp; </p> <ul> <li>Video of the talk is available online at <a title="https://microsoftpdc.com/Sessions/FT20" href="https://microsoftpdc.com/Sessions/FT20" mce_href="https://microsoftpdc.com/Sessions/FT20">https://microsoftpdc.com/Sessions/FT20</a>.&nbsp; <li>Slides and demo content are on Code Gallery at <a title="PDC2009 Demo Code- F# for Parallel And Asynchronous Programming" href="https://code.msdn.microsoft.com/fsharpParallelAsync9" mce_href="https://code.msdn.microsoft.com/fsharpParallelAsync9">PDC2009 Demo Code- F# for Parallel And Asynchronous Programming</a>.</li></ul> <p>The talk begins by covering basic F# concepts, and then focuses on four challenging issues related to concurrency and the tools F# brings for addressing these - immutability, async workflows, and agents.&nbsp; In trying to cover this ground in a 60 minute talk, there were naturally a lot of relevant topics I had to skip, and I also got a number of questions about things I'd glossed over after the talk.&nbsp; So I thought I'd use this post to discuss some of the other features and topics I would have highlighted in this presentation if there'd been more time.<br>&nbsp;</p> <p><i>Note:&nbsp; </i>The topics covered below mostly assume you've either watched the session video or taken a look through the source code attached above.&nbsp; If you haven't yet - check out the talk.</p> <p>&nbsp;</p> <h1>Some F# Parallel and Async Topics</h1> <h2><br>PSeq</h2> <p>The talk briefly shows the use of a PSeq module to write code like the following:</p> <blockquote><pre class="code"><span style="color: blue">let rec </span>sumOfSquares nums =     <br>    nums    <br>    |&gt; PSeq.map sqr    <br>    |&gt; PSeq.sum</pre></blockquote><a href="https://11011.net/software/vspaste" mce_href="https://11011.net/software/vspaste"></a>
<p>As a few folks have noted, the F# core library does not actually provide this PSeq module.&nbsp; In the demo code, I was just using my own little implementation of this, to show off the benefits of the more declarative programming style used here.&nbsp; </p>
<p>The PSeq I used is just a very simple wrapper around the functionality provided in PLinq - for example, PSeq.map just calls ParallelEnumerable.Select.&nbsp; We are expecting a future release of the F# PowerPack to include this wrapper library.&nbsp; In the the meantime, you can check out Matt Podwysocki's blog post on using <a href="https://weblogs.asp.net/podwysocki/archive/2009/02/23/adding-parallel-extensions-to-f.aspx" mce_href="https://weblogs.asp.net/podwysocki/archive/2009/02/23/adding-parallel-extensions-to-f.aspx">PLinq from F#</a>, or Talbot Crowell's recent post with an <a href="https://talbottc.spaces.live.com/blog/cns!A6E0DA836D488CA6!396.entry" mce_href="https://talbottc.spaces.live.com/blog/cns!A6E0DA836D488CA6!396.entry">updated Beta2 version</a>. </p>
<p>&nbsp;</p>
<h2>Using Begin/End Methods with F# Async</h2>
<p>In showing the ease of turning synchronous code which calls long-running I/O operations into asynchronous code, I showed adding the pieces highlighed in <font color="#ff0000">red </font>below to the code below to make it async:</p>
<blockquote><pre class="code"><span style="color: blue">let </span>downloadImageAsync(blob : CloudBlob) =<br>  <font color="#00ff00"><b><font color="#ff0000">async {<br></font></b></font>    <span style="color: blue">let<b><font color="#ff0000">!</font></b> </span>pixels = blob.<b><font color="#ff0000">Async</font></b>DownloadByteArray()<br>    <span style="color: blue">let </span>fileName = <span style="color: maroon">"thumbs-" </span>+ blob.Uri.Segments.[blob.Uri.Segments.Length-<span style="color: brown">1</span>]<br>    <span style="color: blue">use </span>outStream =  File.OpenWrite(fileName)<br>    <span style="color: blue">do<b><font color="#ff0000">!</font></b> </span>outStream.<b><font color="#ff0000">Async</font></b>Write(pixels, <span style="color: brown">0</span>, pixels.Length)<br>    <span style="color: blue"><b><font color="#ff0000">return</font></b> </span>fileName  <b><font color="#ff0000">}</font></b></pre></blockquote><a href="https://11011.net/software/vspaste" mce_href="https://11011.net/software/vspaste"></a>
<p>I got a very good question after the talk though: "Where did the AsyncDownloadByteArray function come from?"&nbsp; </p>
<p>In general, for any asynchronous API provided on the platform, it can be simply wrapped and exposed as a method returning Async&lt;T&gt; to be used within F# async workflows as above.&nbsp; In the core F# libraries, we wrap many of the core async APIs in .NET Framework, providing extension methods on the relevant types.&nbsp; This means that functions like Stream.AsyncWrite used above are available by default in F#.&nbsp; However, CloudBlob.DownloadByteArray is defined in the libraries provided with the Windows Azure SDK, and so we need to create a wrapper.</p>
<p>In fact, the Azure SDK doesn't even provide a BeginDownloadByteArray/EndDownloadByteArray pair - but it does provide a more fundamental async operation BeginDownloadToStream/EndDownloadToStream:</p>
<blockquote><pre class="code"><span style="color: blue">public </span><span style="color: #2b91af">IAsyncResult </span>BeginDownloadToStream(<span style="color: #2b91af">Stream </span>target, <span style="color: #2b91af">AsyncCallback </span>callback, <span style="color: blue">object </span>state);</pre><pre class="code"><span style="color: blue">public void </span>EndDownloadToStream(<span style="color: #2b91af">IAsyncResult </span>asyncResult);</pre></blockquote>
<p>Notably, it's likely that the reason for not including the higher level async operations is just due to the substantial complexity of authoring and maintaining these methods in C# today. Had the Azure team written their API in F#, it's likely they would have found it sufficiently easy to add these.</p>
<p>So, what does the wrapper look like?</p>
<blockquote><pre class="code"><span style="color: blue">type </span>CloudBlob <span style="color: blue">with<br>     </span><span style="color: green">/// Asynchronously download blob contents as an array<br>    </span><span style="color: blue">member </span>blob.AsyncDownloadByteArray() = async {<br>        <span style="color: blue">let </span>ms = <span style="color: blue">new </span>MemoryStream(int blob.Properties.Length)<br>        <span style="color: blue">do! </span>Async.FromBeginEnd(<br>                    (<span style="color: blue">fun </span>(cb,s) <span style="color: blue">-&gt; </span>blob.BeginDownloadToStream(ms,cb,s)),<br>                     blob.EndDownloadToStream)<br>        <span style="color: blue">return </span>ms.ToArray() }</pre></blockquote><a href="https://11011.net/software/vspaste" mce_href="https://11011.net/software/vspaste"></a>
<p>Some notes on this implementation:</p>
<h5>Async.FromBeginEnd</h5>
<p>The key tool for wrapping many .NET async APIs is to use Async.FromBeginEnd.&nbsp; This method takes two functions as arguments - the Begin/End pair of the method being wrapped - and returns a function of type Async&lt;T&gt; where T is the type returned from the End method. When directly wrapping a method, this is often trivial - member foo.AsyncBar() = Async.FromBeginEnd(foo.BeginBar, foo.EndBar).</p>
<h5>Composing Async Operations</h5>
<p>There are generally two ways to create Async&lt;T&gt; values - call a function which returns one, like Async.FromBeginEnd, Stream.AsyncWrite, or Async.Parallel - or write an async {.}&nbsp; block to include any arbitrary F# code as part of the composition.&nbsp; In the case above, we need to both call the underlying Begin/End pair, but also construct a stream to download into, and ultimately return the array of bytes left in the resulting stream.&nbsp; This composition of asynchronous operations with some synchronous code is easy to do inside the async {.} block.</p>
<h5>Other Async Interop Utilities</h5>
<p>We saw details above of wrapping Begin/End pairs as Async&lt;T&gt; objects - there are a few other interesting interop scenarios which are nicely supported by the Async API in F#:</p>
<ul>
<li><b>Async.AsBeginEnd</b> - coverts an async operation into a set of Begin/End/Cancel functions which can be used to expose an implementation of the .NET Asynchronous Programming Model to other .NET consumers. <br>
<li><b>Async.AwaitEvent</b>/<b>AwaitWaitHandle</b>/<b>AwaitIAsyncResult</b>/<b>AwaitTask</b> - there are many other async models used in .NET beyond the APM, and F# provides primitives for easily wrapping any of these.</li></ul>
<p>&nbsp; </p>
<h2>Exceptions with Async</h2>
<p>In the talk, I commented on how hard it is to do correct exception handling with typical asynchronous programming tools available today in C#/VB.&nbsp; But I didn't actually show how much easier this is with F# async workflows.&nbsp; Here's what it looks like to make our downloadImageAsync function robust to the many exceptions that could possibly be raised during it's execution:</p>
<blockquote><pre class="code"><span style="color: blue">let </span>downloadImageAsync(blob : CloudBlob) =  async {<br>    <span style="color: blue">try<br>        let! </span>pixels = blob.AsyncDownloadByteArray()<br>        <span style="color: blue">let </span>fileName = <span style="color: maroon">"thumbs-" </span>+ blob.Uri.Segments.[blob.Uri.Segments.Length-<span style="color: brown">1</span>]<br>        <span style="color: blue">use </span>outStream =  File.OpenWrite(fileName)<br>        <span style="color: blue">do! </span>outStream.AsyncWrite(pixels, <span style="color: brown">0</span>, pixels.Length)<br>        <span style="color: blue">return </span>fileName<br>    <span style="color: blue">with<br>    </span>| e -<span style="color: blue">&gt;<br>        </span>Log.Write(e.ToString())<br>        <span style="color: blue">return </span><span style="color: maroon">""  </span>}</pre></blockquote><a href="https://11011.net/software/vspaste" mce_href="https://11011.net/software/vspaste"></a>
<p>The key here is that exception handling is no different for async code than for synchronous code.&nbsp; Under the hood, F# will ensure that exceptions occurring anywhere in the workflow are bubbled up through the non-blocking calls and ultimately handled by the exception handler code.&nbsp; This will happen as expected even when the code executes on multiple different threads during it's operation.</p>
<p>&nbsp;</p>
<h2>Cancellation with Async</h2>
<p>When we have long-running operations in our programs, as well as making them non-blocking, we very often want to make them cancellable.&nbsp; F# async workflows support cancellation automatically, inserting cancellation checks at each let! or do!, and also at each iteration of a loop.&nbsp; Cancellation is tracked and triggered using the new unified cancellation model in the .NET Framework, "System.Threading.CancellationToken".&nbsp; For example, if we want to make downloadImageAsync cancellable, we simply need to pass in a cancellation token when we start the workflow, and then hook up a button to cancel a running operation.&nbsp; The deltas to the PhotoViewer application are indicated in <font color="#ff0000">red </font>below: </p>
<p><i>F# code:</i></p>
<blockquote><pre class="code"><span style="color: blue">member </span>this.DownloadAll(<font color="#ff0000">cancellationToken</font>) =<br>    <span style="color: blue">let </span>work =<br>        container.ListBlobs()<br>        |&gt; Seq.map (<span style="color: blue">fun </span>blob -<span style="color: blue">&gt;<br>            </span>downloadImageAsync(container.GetBlobReference(blob.Uri.ToString())))<br>        |&gt; Async.Parallel<br>    Async.StartAsTask(work<font color="#ff0000">, cancellationToken = cancellationToken</font>) </pre></blockquote>
<p><i>C# client code:</i></p>
<blockquote><pre class="code"><font color="#ff0000"><span style="color: #2b91af">CancellationTokenSource </span>cancellableWork;</font></pre><font color="#ff0000"><pre class="code"><br></font><span style="color: blue">private void </span>Start_Click(<span style="color: blue">object </span>sender, <span style="color: #2b91af">RoutedEventArgs </span>e){<br><font color="#ff0000">    cancellableWork = new CancellationTokenSource();<br></font>    downloader.DownloadAll(<font color="#ff0000">cancellableWork.Token</font>);<br>}</pre><pre class="code"><br><font color="#ff0000">private void Cancel_Click(object sender, RoutedEventArgs e){<br>    if (cancellableWork != null)<br>        cancellableWork.Cancel();<br>}</font></pre><pre class="code"><font color="#ff0000"></font>&nbsp;</pre></blockquote>
<h2>Other Great F# Async Samples</h2>
<p>Don has recently posted two great articles on some other end-to-end samples built on F# Async.&nbsp; These posts cover many of the same core F# Async topics, plus some additional topics not touched on here.&nbsp; The samples are also a lot of fun, using data pulled from Twitter and Bing Translation services.</p>
<ul>
<li><a href="https://blogs.msdn.com/dsyme/archive/2010/01/09/async-and-parallel-design-patterns-in-f-parallelizing-cpu-and-i-o-computations.aspx" mce_href="https://blogs.msdn.com/dsyme/archive/2010/01/09/async-and-parallel-design-patterns-in-f-parallelizing-cpu-and-i-o-computations.aspx">Async and Parallel Design Patterns in F# Part1: Parallelizing CPU and I/O Computations</a> 
<li><a href="https://blogs.msdn.com/dsyme/archive/2010/01/10/async-and-parallel-design-patterns-in-f-reporting-progress-with-events-plus-twitter-sample.aspx" mce_href="https://blogs.msdn.com/dsyme/archive/2010/01/10/async-and-parallel-design-patterns-in-f-reporting-progress-with-events-plus-twitter-sample.aspx">Async and Parallel Design Patterns in F# Part 2: Reporting Progress with Events (plus Twitter Sample)</a> </li></ul>
<p>&nbsp;</p>
<h1>Summary</h1>
<p>F#'s immutability, async workflows and agents are useful features for enabling easier parallel and asynchronous programming in application code.&nbsp; The PDC talk provides a good starting point for understanding how these features can be applied.&nbsp; The topics above cover a few of the related topics that I've been asked about since then, but there is also much, much more that can be enabled on top of these core features.</p>]]></content:encoded>
    </item>
    <item>
      <title>ICFP Programming Contest 2009</title>
      <link>https://docs.microsoft.com/archive/blogs/lukeh/icfp-programming-contest-2009</link>
      <pubDate>Thu, 25 Jun 2009 23:56:00 GMT</pubDate>
      <dc:creator><![CDATA[Luke Hoban [MS]]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/lukeh/2009/06/25/icfp-programming-contest-2009/</guid>
      <description><![CDATA[This year&rsquo;s ICFP Programming Contest starts today.&nbsp; We&rsquo;ve got a team participating,...]]></description>
      <content:encoded><![CDATA[<p>This year&rsquo;s <a href="https://icfpcontest.org/">ICFP Programming Contest</a> starts today.&nbsp; We&rsquo;ve got a team participating, any other F# teams out there?&nbsp;</p>
<p>Last year, I posted an <a href="https://blogs.msdn.com/lukeh/archive/2008/07/10/icfp-programming-contest.aspx">F# implementation of the 2006 ICFP contest problem</a>, which was an amazing and complex set of puzzles inside a custom virtual machine.&nbsp;&nbsp; Here&rsquo;s a Silverlight version of that virtual machine, implemented on top of the <a href="https://blogs.msdn.com/lukeh/archive/2009/06/26/f-in-silverlight.aspx">Console sample</a> I posted yesterday.</p>
<h2>Silverlight UM &ndash; ICFP 2006</h2>
<p>See <a title="https://boundvariable.org/" href="https://boundvariable.org/">https://boundvariable.org/</a> and my <a href="https://blogs.msdn.com/lukeh/archive/2008/07/10/icfp-programming-contest.aspx">previous post</a> for details of what&rsquo;s running in this console.</p>
<p><strong><span style="font-size: x-large;"><a href="https://lukeh-blog.azurewebsites.net/UMTestPage.aspx" target="_blank">Launch the UM</a></span></strong></p>
<pre class="code"><span style="color: green;"> /// Start the UM running on a background thread.<br /> /// The input and output functions will be called on the <br /> /// background thread, and block the execution of the UM<br /> </span><span style="color: blue;">static member </span>Launch(binaryUri : Uri, input : Stream, output : Stream) =<br />     async {<br />         <span style="color: blue;">try<br /> let </span>writer = <span style="color: blue;">new </span>System.IO.StreamWriter(output, AutoFlush=<span style="color: blue;">true</span>)<br />             <span style="color: blue;">let </span>reader = <span style="color: blue;">new </span>System.IO.StreamReader(input)<br />             <span style="color: blue;">do </span>writer.WriteLine(<span style="color: maroon;">"Press &lt;enter&gt; to begin. Note: Will download a large UMIX image."</span>)<br />             <span style="color: blue;">do </span>reader.ReadLine() |&gt; ignore<br />             <span style="color: blue;">let </span>request = System.Net.WebRequest.Create(binaryUri)<br />             <span style="color: blue;">do </span>writer.WriteLine(binaryUri)<br />             <span style="color: blue;">let! </span>response = request.AsyncGetResponse()<br />             <span style="color: blue;">let </span>stream = response.GetResponseStream()<br />             <span style="color: blue;">do </span>writer.WriteLine(<span style="color: maroon;">"Downloading..."</span>)<br />             <span style="color: blue;">let </span>progress(percent) = writer.WriteLine(<span style="color: maroon;">"Downloaded: "</span>+percent.ToString()+<span style="color: maroon;">"%"</span>)<br />             <span style="color: blue;">let! </span>bytes = asyncReadAllBytesFromStreamWithProgress (stream, int response.ContentLength, progress)<span style="color: blue;"> <br /> do </span>writer.WriteLine(<span style="color: maroon;">"Booting..."</span>)<br />             <span style="color: blue;">let </span>ee = UM(bytes, Func&lt;int&gt;(input.ReadByte), Action&lt;byte&gt;(output.WriteByte))<br />             ee.Run()<br />         <span style="color: blue;">with<br /> </span>| e <span style="color: blue;">-&gt; </span>System.Diagnostics.Debug.WriteLine(<span style="color: maroon;">"UM failed with {0}"</span>, e)<br />     } |&gt; Async.Start     </pre>
<h3>F# Async in Silverlight</h3>
<p>In Silverlight, the APIs for synchronous I/O have been removed, which forces developers to do the &lsquo;right thing&rsquo; and make async calls for long-running I/O operations, thus (hopefully) keeping the UI responsive.&nbsp; This makes F# a really nice implementation language for Silverlight applications, using F#&rsquo;s async workflows.&nbsp; In the code above, an asynchronous workflow describes the flow of control of launching the UM.&nbsp; At the two points of long running network connections, async calls are made with &ldquo;let!&rdquo;, so that the UI thread is not blocked and the application remains responsive.&nbsp; This ultimately hides a lot of complexity that would be added in chaining these asynchronous operations together in a standard .NET approach to this.</p>
<p>Note also that the code above calls a helper function &ldquo;asyncReadAllBytesFromStreamWithProgress&rdquo;, which shows how async code in F# can be nicely factored using the same sort of &ldquo;extract method&rdquo; factoring you are used to in synchronous programming.&nbsp; The implementation of this helper also shows that async calls with &lsquo;let!&rsquo; can be placed inside &lsquo;for&rsquo; and &lsquo;while&rsquo; loops.&nbsp; Chances are you don&rsquo;t even want to try doing that with standard Begin/End calls!</p>
<pre class="code"><span style="color: blue;">let internal </span>asyncReadAllBytesFromStreamWithProgress(stream:Stream, length:int, progress:int-&gt;unit) =<br />    async {<br />        <span style="color: blue;">let </span>offset = ref 0<br />        <span style="color: blue;">let </span>count = ref length<br />        <span style="color: blue;">let </span>buffer = Array.zeroCreate&lt;byte&gt; !count<br />        <span style="color: blue;">while </span>!count &gt; 0 <span style="color: blue;">do<br /> let! </span>bytesRead = stream.AsyncRead(buffer, !offset, (min 524288 !count))<br />            <span style="color: blue;">if </span>bytesRead = 0 <span style="color: blue;">then </span>raise (<span style="color: blue;">new </span>EndOfStreamException(<span style="color: maroon;">"Read beyond the EOF"</span>))<br />            <span style="color: blue;">do </span>offset := !offset + bytesRead<br />            <span style="color: blue;">do </span>count := !count - bytesRead<br />            progress(100 * !offset / length)<br />        <span style="color: blue;">return </span>buffer<br />    }</pre>
<h3>Consuming F# from C#+XAML</h3>
<p>The majority of this app is written in F# &ndash; the console control is authored in F# and the application logic is in F#.&nbsp; Here is the C# and XAML that ties it together:</p>
<pre class="code"><span style="color: blue;">&lt;</span><span style="color: #a31515;">UserControl </span><span style="color: red;">xmlns</span><span style="color: blue;">:</span><span style="color: red;">my</span><span style="color: blue;">="clr-namespace:System.Windows.Controls;assembly=SilverlightConsole" </span><span style="color: red;">x</span><span style="color: blue;">:</span><span style="color: red;">Class</span><span style="color: blue;">="UM.Page"<br /> </span><span style="color: red;">xmlns</span><span style="color: blue;">=<a href="https://schemas.microsoft.com/winfx/2006/xaml/presentation">https://schemas.microsoft.com/winfx/2006/xaml/presentation</a><br /> </span><span style="color: red;">xmlns</span><span style="color: blue;">:</span><span style="color: red;">x</span><span style="color: blue;">=<a href="https://schemas.microsoft.com/winfx/2006/xaml">https://schemas.microsoft.com/winfx/2006/xaml</a><br /> </span><span style="color: red;">Width</span><span style="color: blue;">="600" </span><span style="color: red;">Height</span><span style="color: blue;">="400"&gt;<br /> &lt;</span><span style="color: #a31515;">Grid </span><span style="color: red;">x</span><span style="color: blue;">:</span><span style="color: red;">Name</span><span style="color: blue;">="LayoutRoot" </span><span style="color: red;">Background</span><span style="color: blue;">="White"&gt;<br /> &lt;</span><span style="color: #a31515;">my</span><span style="color: blue;">:</span><span style="color: #a31515;">SilverlightConsole </span><span style="color: red;">x</span><span style="color: blue;">:</span><span style="color: red;">Name</span><span style="color: blue;">="console" </span><span style="color: red;">Width</span><span style="color: blue;">="600" </span><span style="color: red;">Height</span><span style="color: blue;">="400"<br /> </span><span style="color: red;">FontFamily</span><span style="color: blue;">="Courier New" </span><span style="color: red;">FontSize</span><span style="color: blue;">="13" </span><span style="color: red;">FontWeight</span><span style="color: blue;">="Bold"<br /> </span><span style="color: red;">Foreground</span><span style="color: blue;">="GreenYellow" </span><span style="color: red;">Background</span><span style="color: blue;">="Black" </span><span style="color: red;">Text</span><span style="color: blue;">="" /&gt;<br /> &lt;/</span><span style="color: #a31515;">Grid</span><span style="color: blue;">&gt;<br />&lt;/</span><span style="color: #a31515;">UserControl</span><span style="color: blue;">&gt;</span></pre>
<pre class="code"><span style="color: blue;">public partial class </span><span style="color: #2b91af;">Page </span>: <span style="color: #2b91af;">UserControl </span>{<br />    <span style="color: blue;">public </span>Page() {<br />        InitializeComponent();<br />        <span style="color: #2b91af;">Uri </span>curPage = System.Windows.<span style="color: #2b91af;">Application</span>.Current.Host.Source;<br />        <span style="color: #2b91af;">UriBuilder </span>builder = <span style="color: blue;">new </span><span style="color: #2b91af;">UriBuilder</span>(curPage.Scheme, curPage.Host, curPage.Port, <span style="color: #a31515;">"umix.dll"</span>);<br />        <span style="color: #2b91af;">ICFP</span>.<span style="color: #2b91af;">UM</span>.Launch(builder.Uri, console.InputStream, console.OutputStream);<br />    }<br />}</pre>
<h2>Summary</h2>
<p>Check out ICFP Programming Contest&nbsp; 2009 this weekend, and take F#+Async+Silverlight for a spin.</p>]]></content:encoded>
    </item>
    <item>
      <title>F# in Silverlight</title>
      <link>https://docs.microsoft.com/archive/blogs/lukeh/f-in-silverlight</link>
      <pubDate>Thu, 25 Jun 2009 21:46:00 GMT</pubDate>
      <dc:creator><![CDATA[Luke Hoban [MS]]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/lukeh/2009/06/25/f-in-silverlight/</guid>
      <description><![CDATA[Over the last couple years, there has been an explosion of interest in Silverlight.&nbsp; As a...]]></description>
      <content:encoded><![CDATA[<p>Over the last couple years, there has been an explosion of interest in Silverlight.&nbsp; As a .NET-based runtime, it is possible to compile Silverlight applications with any .NET language, and we&rsquo;ve seen a lot of F# developers using F# in Silverlight.&nbsp; However, until recently this involved building an application using the desktop version of the F# runtime, which could result in some pitfalls and mixed levels of success.</p>
<p>With the recent F# May CTP though, we now provide a Silverlight version of the F# runtime, FSharp.Core.dll, along with the F# release.&nbsp; This enables building truly first-class Silverlight components using F#.</p>
<p>To make this easier, I&rsquo;ve posted some Silverlight F# project templates and samples on Code Gallery.&nbsp;</p>
<h2>Download</h2>
<p><a href="https://code.msdn.microsoft.com/fsharpsilverlight">F# Templates and Samples for Silverlight</a></p>
<h2>Templates</h2>
<p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/lukeh/WindowsLiveWriter/FinSilverlight_131CF/image_2.png" original-url="https://blogs.msdn.com/blogfiles/lukeh/WindowsLiveWriter/FinSilverlight_131CF/image_2.png"><img style="display: inline; border-width: 0px;" title="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/lukeh/WindowsLiveWriter/FinSilverlight_131CF/image_thumb.png" original-url="https://blogs.msdn.com/blogfiles/lukeh/WindowsLiveWriter/FinSilverlight_131CF/image_thumb.png" alt="image" width="634" height="483" border="0" /></a></p>
<h2>Samples</h2>
<h3>L-Systems</h3>
<p>Lindenmayer Systems are an interesting way of generating a variety of fractals using a simple set of rewrite rules.&nbsp; Check out the fascinating book <a href="https://algorithmicbotany.org/papers/abop/abop.lowquality.pdf">The Algorithmic Beauty of Plants</a> for details.&nbsp; The Silverlight application below uses an L-System rewriter and rendered written in F#.</p>
<ul>
<li><strong>F, G, A, B</strong> are drawn as a move forward.</li>
<li><strong>+</strong> is a turn right.</li>
<li><strong>-</strong> is a turn right.</li>
<li><strong>X, Y</strong>and anything else is skipped during rendering.</li>
</ul>
<p><span style="font-size: x-large;"><a href="https://lukeh-blog.azurewebsites.net/LSystemTestPage.aspx" target="_blank">Launch the L-System demo</a></span>&nbsp;</p>
<pre class="code"><span style="color: blue;">open </span>System.Windows
<span style="color: blue;">open </span>System.Windows.Shapes

<span style="color: blue;">let rec internal </span>applyRulesInOrder rules c =
    <span style="color: blue;">match </span>rules <span style="color: blue;">with</span>
    | [] <span style="color: blue;">-&gt; </span>string c
    | rule::rules' <span style="color: blue;">-&gt; match </span>rule c <span style="color: blue;">with </span>| None <span style="color: blue;">-&gt; </span>applyRulesInOrder rules' c
        | Some result <span style="color: blue;">-&gt; </span>result

<span style="color: blue;">let internal </span>step rules current =
     current
     |&gt; String.collect (applyRulesInOrder rules)

<span style="color: blue;">let internal </span>rotate (x,y) theta =
    <span style="color: blue;">let </span>x' = x * cos theta - y * sin theta
    <span style="color: blue;">let </span>y' = x * sin theta + y * cos theta
    (x',y')

<span style="color: blue;">let rec internal </span>render (x,y) (dx,dy) angle points system =
    <span style="color: blue;">match </span>system <span style="color: blue;">with </span>| [] <span style="color: blue;">-&gt; </span>(x,-y)::points
    | <span style="color: maroon;">'A'</span>::system' | <span style="color: maroon;">'B'</span>::system' | <span style="color: maroon;">'F'</span>::system' | <span style="color: maroon;">'G'</span>::system' <span style="color: blue;">-&gt; let </span>x',y' = x+dx,y+dy
        render (x',y') (dx,dy) angle ((x,-y)::points)  system'
    | <span style="color: maroon;">'+'</span>::system' <span style="color: blue;">-&gt; let </span>(dx',dy') = rotate (dx,dy) angle
        render (x,y) (dx',dy') angle points system'
    | <span style="color: maroon;">'-'</span>::system' <span style="color: blue;">-&gt; let </span>(dx',dy') = rotate (dx,dy) (-angle)
        render (x,y) (dx',dy') angle points system'
    | _::system' <span style="color: blue;">-&gt; </span>render (x,y) (dx,dy) angle points system'<span style="color: blue;"> let rec internal </span>applyN f n x =
    <span style="color: blue;">if </span>n = 0 <span style="color: blue;">then </span>x
    <span style="color: blue;">else </span>f (applyN f (n-1) x)

<span style="color: blue;">let internal </span>normalize points =
    <span style="color: blue;">let </span>minX = points |&gt; Seq.map (<span style="color: blue;">fun </span>(x,_) <span style="color: blue;">-&gt; </span>x) |&gt; Seq.min
    <span style="color: blue;">let </span>minY = points |&gt; Seq.map (<span style="color: blue;">fun </span>(_,y) <span style="color: blue;">-&gt; </span>y) |&gt; Seq.min
    points |&gt; List.map (<span style="color: blue;">fun </span>(x,y) <span style="color: blue;">-&gt; new </span>Point(x-minX, y-minY))<span style="color: blue;"> type </span>LSystem(rulesString:string, start:string, angle:int, stepSize:int, n:int) =
    <span style="color: blue;">let </span>expanded,isError =
        <span style="color: blue;">try let </span>rules =
                rulesString.Split([|<span style="color: maroon;">"\r"</span>;<span style="color: maroon;">"\n"</span>|], System.StringSplitOptions.RemoveEmptyEntries)
                |&gt; Array.map (<span style="color: blue;">fun </span>line <span style="color: blue;">-&gt; </span>line.Split([|<span style="color: maroon;">"-&gt;"</span>|], System.StringSplitOptions.RemoveEmptyEntries))
                |&gt; Array.map (<span style="color: blue;">fun </span>fromAndTo <span style="color: blue;">-&gt; </span>(fromAndTo.[0].[0], fromAndTo.[1]))
            <span style="color: blue;">let </span>ruleFunctions = [ <span style="color: blue;">for </span>(c, s) <span style="color: blue;">in </span>rules <span style="color: blue;">-&gt; fun </span>x <span style="color: blue;">-&gt; if </span>x = c <span style="color: blue;">then </span>Some s <span style="color: blue;">else </span>None]
            applyN (step ruleFunctions) n start, <span style="color: blue;">false with </span>| e <span style="color: blue;">-&gt; </span><span style="color: maroon;">""</span>, <span style="color: blue;">true member </span>this.Render(polyline : Polyline) =
        <span style="color: blue;">let </span>points = render (0.0,0.0) (float stepSize,0.0) (float angle * System.Math.PI / 180.0) [] (List.ofSeq expanded)
        <span style="color: blue;">for </span>pt <span style="color: blue;">in </span>normalize points <span style="color: blue;">do </span>polyline.Points.Add(pt)
        isError

        </pre>
<h3>Console Control</h3>
<p>A resuable Silverlight control providing a console emulation. The control exposes input and ouput streams akin to those on the System.Console class. Could be used to provide console input and output as part of a Silverlight application, or as a way to convert Windows Console apps to Silverlight apps.</p>
<p>This samples hooks the Console up to a simple echo loop.</p>
<p><span style="font-size: x-large;"><a href="https://lukeh-blog.azurewebsites.net/SilverlightConsoleEchoTestPage.aspx" target="_blank">Launch the Console Control</a></span></p>
<pre class="code"><span style="color: blue;">namespace </span>System.Windows.Controls

<span style="color: blue;">open </span>System
<span style="color: blue;">open </span>System.IO
<span style="color: blue;">open </span>System.Windows
<span style="color: blue;">open </span>System.Windows.Controls
<span style="color: blue;">open </span>System.Windows.Input
<span style="color: blue;">open </span>SilverlightContrib.Utilities.ClipboardHelper
<span style="color: blue;">open </span>System.Text

<span style="color: green;">// A shared base implementation of Stream for <br />// use by the console input and output streams</span>
[&lt;AbstractClass&gt;]<span style="color: blue;"> type private </span>ConsoleStream(isRead) = 
    <span style="color: blue;">inherit </span>Stream()
    <span style="color: blue;">override </span>this.CanRead = isRead
    <span style="color: blue;">override </span>this.CanWrite = not isRead
    <span style="color: blue;">override </span>this.CanSeek = <span style="color: blue;">false override </span>this.Position
        <span style="color: blue;">with </span>get() = raise (<span style="color: blue;">new </span>NotSupportedException(<span style="color: maroon;">"Console stream does not have a position"</span>))
        <span style="color: blue;">and </span>set(v) = raise (<span style="color: blue;">new </span>NotSupportedException(<span style="color: maroon;">"Console stream does not have a position"</span>))
    <span style="color: blue;">override </span>this.Length = raise (<span style="color: blue;">new </span>NotSupportedException(<span style="color: maroon;">"Console stream does not have a length"</span>))
    <span style="color: blue;">override </span>this.Flush() = ()
    <span style="color: blue;">override </span>this.Seek(offset, origin) = raise (<span style="color: blue;">new </span>NotSupportedException(<span style="color: maroon;">"Console stream cannot seek"</span>))
    <span style="color: blue;">override </span>this.SetLength(v) = raise (<span style="color: blue;">new </span>NotSupportedException(<span style="color: maroon;">"Console stream does not have a length"</span>)) 

<span style="color: green;">/// A control representing a Console window <br />/// Provides an InputStream and OutputStream <br />/// for reading an writing character input. <br />/// Also supports copy/paste on some browsers</span>
<span style="color: blue;">type </span>SilverlightConsole() <span style="color: blue;">as </span>self = 
    <span style="color: blue;">inherit </span>TextBox()

    <span style="color: green;">// The queue of user input which has been collected by the <br /> // console, but not yet read from the input stream <br /></span><span style="color: blue;"> let </span>readQueue = <span style="color: blue;">new </span>System.Collections.Generic.Queue&lt;int&gt;()

    <span style="color: green;">// A stream that reads characters from user input <br /></span><span style="color: blue;"> let </span>inputStream = 
        { <span style="color: blue;">new </span>ConsoleStream(<span style="color: blue;">true</span>) <span style="color: blue;">with override </span>this.Write(buffer,offset,count) = 
                raise (<span style="color: blue;">new </span>NotSupportedException(<span style="color: maroon;">"Cannot write from Console input stream"</span>))
            <span style="color: blue;">override </span>this.Read(buffer,offset,count) = 
                <span style="color: blue;">do </span>System.Diagnostics.Debug.WriteLine(<span style="color: maroon;">"Starting to read {0} bytes"</span>, count)
                <span style="color: blue;">let rec </span>waitForAtLeastOneByte() =
                    <span style="color: blue;">let </span>shouldSleep = ref <span style="color: blue;">true let </span>ret = ref [||]
                    lock readQueue  (<span style="color: blue;">fun </span>() <span style="color: blue;">-&gt; </span>shouldSleep := readQueue.Count &lt; 1
                        <span style="color: blue;">if </span>not !shouldSleep <span style="color: blue;">then let </span>lengthToRead = min readQueue.Count count
                            ret := Array.init lengthToRead (<span style="color: blue;">fun </span>i <span style="color: blue;">-&gt; </span>byte (readQueue.Dequeue())))
                    <span style="color: blue;">if </span>!shouldSleep
                    <span style="color: blue;">then </span>System.Threading.Thread.Sleep(100); waitForAtLeastOneByte()
                    <span style="color: blue;">else </span>!ret
                <span style="color: blue;">let </span>bytes = waitForAtLeastOneByte()
                System.Array.Copy(bytes, 0, buffer, offset, bytes.Length)
                <span style="color: blue;">do </span>System.Diagnostics.Debug.WriteLine(<span style="color: maroon;">"Finished reading {0} bytes"</span>, bytes.Length)
                bytes.Length
        }

    <span style="color: green;">// A stream that sends character output onto the console screen <br /></span><span style="color: blue;"> let </span>outputStream =
        { <span style="color: blue;">new </span>ConsoleStream(<span style="color: blue;">false</span>) <span style="color: blue;">with override </span>this.Read(buffer,offset,count) = 
                raise (<span style="color: blue;">new </span>NotSupportedException(<span style="color: maroon;">"Cannot read from Console output stream"</span>))
            <span style="color: blue;">override </span>this.Write(buffer,offset,count) = 
                <span style="color: blue;">let </span>isDelete = offset &lt; 0
                <span style="color: blue;">let </span>newText =
                     <span style="color: blue;">if </span>isDelete
                     <span style="color: blue;">then </span><span style="color: maroon;">"" </span><span style="color: blue;">else </span>UnicodeEncoding.UTF8.GetString(buffer, offset, count)
                <span style="color: blue;">let </span>_ = self.Dispatcher.BeginInvoke(<span style="color: blue;">fun </span>() <span style="color: blue;">-&gt; if </span>isDelete <span style="color: blue;">then if </span>self.Text.Length &gt;= count <span style="color: blue;">then </span>self.Text &lt;- self.Text.Substring(0, self.Text.Length - count)
                    <span style="color: blue;">else do </span>self.Text &lt;- self.Text + newText
                    <span style="color: blue;">do </span>self.SelectionStart &lt;- self.Text.Length
                    <span style="color: blue;">do </span>self.SelectionLength &lt;- 0)
                ()
        }

    <span style="color: blue;">let </span>shiftNumbers = [|<span style="color: maroon;">')'</span>;<span style="color: maroon;">'!'</span>;<span style="color: maroon;">'@'</span>;<span style="color: maroon;">'#'</span>;<span style="color: maroon;">'$'</span>;<span style="color: maroon;">'%'</span>;<span style="color: maroon;">'^'</span>;<span style="color: maroon;">'&amp;'</span>;<span style="color: maroon;">'*'</span>;<span style="color: maroon;">'('</span>|]
    <span style="color: blue;">let </span>currentInputLine = <span style="color: blue;">new </span>System.Collections.Generic.List&lt;int&gt;()

    <span style="color: green;">// Handles key down events <br /> // Processes the pressed key and turns it into console input <br /> // Also echos the pressed key to the console <br /></span><span style="color: blue;"> let </span>keyDownHandler(keyArgs : KeyEventArgs) =
        <span style="color: blue;">try do </span>keyArgs.Handled &lt;- <span style="color: blue;">true let </span>shiftDown = Keyboard.Modifiers &amp;&amp;&amp; ModifierKeys.Shift &lt;&gt; (enum 0)
            <span style="color: blue;">let </span>ctrlDown = Keyboard.Modifiers &amp;&amp;&amp; ModifierKeys.Control &lt;&gt; (enum 0)
            <span style="color: blue;">let </span>p = keyArgs.PlatformKeyCode
            <span style="color: blue;">if </span>ctrlDown || keyArgs.Key = Key.Ctrl <span style="color: blue;">then if </span>keyArgs.Key = Key.V <span style="color: blue;">then </span>lock currentInputLine (<span style="color: blue;">fun </span>() <span style="color: blue;">-&gt; let </span>clipboard = <span style="color: blue;">new </span>ClipboardHelper()
                        <span style="color: blue;">let </span>fromClipboard = clipboard.GetData()
                        <span style="color: blue;">for </span>c <span style="color: blue;">in </span>fromClipboard <span style="color: blue;">do do </span>currentInputLine.Add(int c)
                            outputStream.WriteByte(byte c)
                            <span style="color: blue;">if </span>c = <span style="color: maroon;">'\n' </span><span style="color: blue;">then for </span>i <span style="color: blue;">in </span>currentInputLine <span style="color: blue;">do do </span>System.Diagnostics.Debug.WriteLine(<span style="color: maroon;">"Enqueued {0}"</span>, char i)
                                    <span style="color: blue;">do </span>readQueue.Enqueue(i)
                                <span style="color: blue;">do </span>currentInputLine.Clear()
                    )
                <span style="color: blue;">elif </span>keyArgs.Key = Key.C <span style="color: blue;">then let </span>text = self.SelectedText
                    <span style="color: blue;">let </span>clipboard = <span style="color: blue;">new </span>ClipboardHelper()
                    clipboard.SetData(text)
            <span style="color: blue;">else </span>System.Diagnostics.Debug.WriteLine(<span style="color: maroon;">"Got key {0} {1} {2}"</span>, p, char p, keyArgs.Key)
                <span style="color: blue;">let </span>ascii =
                    <span style="color: blue;">match </span>p <span style="color: blue;">with </span>| n <span style="color: blue;">when </span>n &gt;= 65 &amp;&amp; n &lt;= 90 <span style="color: blue;">-&gt; if </span>shiftDown <span style="color: blue;">then </span>p <span style="color: blue;">else </span>p+32
                    | n <span style="color: blue;">when </span>n &gt;= 48 &amp;&amp; n &lt;= 57 <span style="color: blue;">-&gt; if </span>shiftDown <span style="color: blue;">then </span>int shiftNumbers.[p-48] <span style="color: blue;">else </span>p
                    | 8 <span style="color: blue;">-&gt; </span>8 <br /><span style="color: green;"> // backspace <br /></span>                    | 13 <span style="color: blue;">-&gt; </span>int <span style="color: maroon;">'\n' <br /></span>                    | 32 <span style="color: blue;">-&gt; </span>int <span style="color: maroon;">' ' <br /></span>                    | 186 <span style="color: blue;">-&gt; if </span>shiftDown <span style="color: blue;">then </span>int <span style="color: maroon;">':' </span><span style="color: blue;">else </span>int <span style="color: maroon;">';' <br /></span>                    | 187 <span style="color: blue;">-&gt; if </span>shiftDown <span style="color: blue;">then </span>int <span style="color: maroon;">'+' </span><span style="color: blue;">else </span>int <span style="color: maroon;">'=' <br /></span>                    | 188 <span style="color: blue;">-&gt; if </span>shiftDown <span style="color: blue;">then </span>int <span style="color: maroon;">'&lt;' </span><span style="color: blue;">else </span>int <span style="color: maroon;">',' <br /></span>                    | 189 <span style="color: blue;">-&gt; if </span>shiftDown <span style="color: blue;">then </span>int <span style="color: maroon;">'_' </span><span style="color: blue;">else </span>int <span style="color: maroon;">'-' <br /></span>                    | 190 <span style="color: blue;">-&gt; if </span>shiftDown <span style="color: blue;">then </span>int <span style="color: maroon;">'&gt;' </span><span style="color: blue;">else </span>int <span style="color: maroon;">'.' <br /></span>                    | 191 <span style="color: blue;">-&gt; if </span>shiftDown <span style="color: blue;">then </span>int <span style="color: maroon;">'?' </span><span style="color: blue;">else </span>int <span style="color: maroon;">'/' <br /></span>                    | 192 <span style="color: blue;">-&gt; if </span>shiftDown <span style="color: blue;">then </span>int <span style="color: maroon;">'~' </span><span style="color: blue;">else </span>int <span style="color: maroon;">'`' <br /></span>                    | 219 <span style="color: blue;">-&gt; if </span>shiftDown <span style="color: blue;">then </span>int <span style="color: maroon;">'{' </span><span style="color: blue;">else </span>int <span style="color: maroon;">'[' <br /></span>                    | 220 <span style="color: blue;">-&gt; if </span>shiftDown <span style="color: blue;">then </span>int <span style="color: maroon;">'|' </span><span style="color: blue;">else </span>int <span style="color: maroon;">'\\' <br /></span>                    | 221 <span style="color: blue;">-&gt; if </span>shiftDown <span style="color: blue;">then </span>int <span style="color: maroon;">'}' </span><span style="color: blue;">else </span>int <span style="color: maroon;">']' <br /></span>                    | 222 <span style="color: blue;">-&gt; if </span>shiftDown <span style="color: blue;">then </span>int <span style="color: maroon;">'\"' </span><span style="color: blue;">else </span>int <span style="color: maroon;">'\'' <br /></span>                    | _ <span style="color: blue;">-&gt; </span>-1
                <span style="color: blue;">if </span>ascii = 8 <span style="color: blue;">then </span>lock currentInputLine (<span style="color: blue;">fun </span>() <span style="color: blue;">-&gt; if </span>currentInputLine.Count &gt; 0 <span style="color: blue;">then </span>currentInputLine.RemoveAt(currentInputLine.Count - 1)
                        outputStream.Write([||], -1, 1)
                    )
                <span style="color: blue;">elif </span>ascii &gt; 0 <span style="color: blue;">then </span>lock currentInputLine (<span style="color: blue;">fun </span>() <span style="color: blue;">-&gt; do </span>currentInputLine.Add(ascii)
                        outputStream.WriteByte(byte ascii)
                    )
                <span style="color: blue;">if </span>ascii = int <span style="color: maroon;">'\n' </span><span style="color: blue;">then </span>lock currentInputLine (<span style="color: blue;">fun </span>() <span style="color: blue;">-&gt; for </span>i <span style="color: blue;">in </span>currentInputLine <span style="color: blue;">do do </span>System.Diagnostics.Debug.WriteLine(<span style="color: maroon;">"Enqueued {0}"</span>, char i)
                            <span style="color: blue;">if </span>i = 10 <span style="color: blue;">then do </span>readQueue.Enqueue(13)
                            <span style="color: blue;">do </span>readQueue.Enqueue(i)
                        <span style="color: blue;">do </span>currentInputLine.Clear())
                <span style="color: blue;">do </span>self.SelectionStart &lt;- self.Text.Length
                <span style="color: blue;">do </span>self.SelectionLength &lt;- 0
        <span style="color: blue;">with </span>| e <span style="color: blue;">-&gt; </span>System.Diagnostics.Debug.WriteLine(e)

    <span style="color: green;">// Lazily initialized StreamReader/StreamWriter <br /></span><span style="color: blue;"> let </span>outReader = <span style="color: blue;">lazy </span>(<span style="color: blue;">new </span>System.IO.StreamWriter(outputStream, Encoding.UTF8, 256, AutoFlush=<span style="color: blue;">true</span>))
    <span style="color: blue;">let </span>inReader = <span style="color: blue;">lazy </span>(<span style="color: blue;">new </span>System.IO.StreamReader(inputStream, Encoding.UTF8, <span style="color: blue;">false</span>, 256))

    <span style="color: green;">// Manually handle the Return key so we can accept newlines <br /></span><span style="color: blue;"> do </span>self.AcceptsReturn &lt;- <span style="color: blue;">true <br /></span><span style="color: green;"> // Make sure a vertical scrollbar appears when needed <br /></span><span style="color: blue;"> do </span>self.VerticalScrollBarVisibility &lt;- ScrollBarVisibility.Auto
    <span style="color: green;">// Make the control read-only so that users cannot move the cusor or change the contents <br /> // Unfortunatley, this also greys it out - ideally we could seperate theese two. <br /></span><span style="color: blue;"> do </span>self.IsReadOnly &lt;- <span style="color: blue;">true <br /></span><span style="color: green;"> // Hookup the keyDownHandler <br /></span><span style="color: blue;"> do </span>self.KeyDown.Add(keyDownHandler)

    <span style="color: green;">/// The raw input stream for the Console <br /></span><span style="color: blue;"> member </span>this.InputStream = inputStream :&gt; Stream
    <span style="color: green;">/// The raw ouput stream for the Console <br /></span><span style="color: blue;"> member </span>this.OutputStream = outputStream :&gt; Stream

    <span style="color: green;">/// A StreamWriter for writing to the Console <br /></span><span style="color: blue;"> member </span>this.Out = outReader.Value
    <span style="color: green;">/// A StreamReader for reading from the Console <br /></span><span style="color: blue;"> member </span>this.In = inReader.Value
</pre>
<h2>Summary</h2>
<p>Try out F# with Silverlight using the F# May CTP and the F# for Silverlight templates.</p>]]></content:encoded>
    </item>
    <item>
      <title>F# on Windows Azure</title>
      <link>https://docs.microsoft.com/archive/blogs/lukeh/f-on-windows-azure</link>
      <pubDate>Tue, 28 Oct 2008 10:40:00 GMT</pubDate>
      <dc:creator><![CDATA[Luke Hoban [MS]]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/lukeh/2008/10/28/f-on-windows-azure/</guid>
      <description><![CDATA[Windows Azure was announced yesterday, and along with it, the first CTP of the SDK and Visual Studio...]]></description>
      <content:encoded><![CDATA[<P><A href="https://www.microsoft.com/azure/default.mspx" mce_href="https://www.microsoft.com/azure/default.mspx">Windows Azure</A> was announced yesterday, and along with it, the first CTP of the <A href="https://www.microsoft.com/downloads/details.aspx?FamilyId=BB893FB0-AD04-4FE8-BB04-0C5E4278D3E9&amp;displaylang=en" mce_href="https://www.microsoft.com/downloads/details.aspx?FamilyId=BB893FB0-AD04-4FE8-BB04-0C5E4278D3E9&amp;displaylang=en">SDK</A> and <A href="https://go.microsoft.com/fwlink/?LinkId=128752" mce_href="https://go.microsoft.com/fwlink/?LinkId=128752">Visual Studio tools</A>.&nbsp; If you haven’t yet tried it, go <A href="https://www.microsoft.com/azure/register.mspx" mce_href="https://www.microsoft.com/azure/register.mspx">take a look</A>.&nbsp; On top of serving as a hosting service for web applications, Azure also provides a really simple way to do distributed compute and storage in the cloud.</P>
<P>Azure supports running .NET applications, which means you can build Azure worker roles using F#! The tools released with Azure don’t have F# support out of the box though, so I’ve posted a few simple templates and samples up on Code Gallery.</P>
<H2>Download</H2>
<P><A href="https://code.msdn.microsoft.com/fsharpazure/" mce_href="https://code.msdn.microsoft.com/fsharpazure/">F# Templates and Samples for Windows Azure</A></P>
<H2>Templates</H2>
<P><A href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/lukeh/WindowsLiveWriter/FonWindowsAzure_801/image_2.png" original-url="https://blogs.msdn.com/blogfiles/lukeh/WindowsLiveWriter/FonWindowsAzure_801/image_2.png" mce_href="https://blogs.msdn.com/blogfiles/lukeh/WindowsLiveWriter/FonWindowsAzure_801/image_2.png"><IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px" title=image border=0 alt=image src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/lukeh/WindowsLiveWriter/FonWindowsAzure_801/image_thumb.png" original-url="https://blogs.msdn.com/blogfiles/lukeh/WindowsLiveWriter/FonWindowsAzure_801/image_thumb.png" width=634 height=390 mce_src="https://blogs.msdn.com/blogfiles/lukeh/WindowsLiveWriter/FonWindowsAzure_801/image_thumb.png"></A> </P>
<H2>Cloud WebCrawl Sample</H2><PRE class=code><SPAN style="COLOR: blue">namespace <FONT color=#000000>SearchEngine_WorkerRole

</FONT><SPAN style="COLOR: blue">open </SPAN><FONT color=#000000>System
</FONT><SPAN style="COLOR: blue">open </SPAN><FONT color=#000000>System.Threading
</FONT><SPAN style="COLOR: blue">open </SPAN><FONT color=#000000>Microsoft.ServiceHosting.ServiceRuntime
</FONT><SPAN style="COLOR: blue">open </SPAN><FONT color=#000000>System.Net
</FONT><SPAN style="COLOR: blue">open </SPAN><FONT color=#000000>System.IO
</FONT><SPAN style="COLOR: blue">open </SPAN><FONT color=#000000>System.Text.RegularExpressions
</FONT><SPAN style="COLOR: blue">open </SPAN><FONT color=#000000>Microsoft.Samples.ServiceHosting.StorageClient;
</FONT><SPAN style="COLOR: blue">open </SPAN><FONT color=#000000>System.Web
</FONT><SPAN style="COLOR: blue">open </SPAN><FONT color=#000000>System.Runtime.Serialization.Formatters.Binary

</FONT><SPAN style="COLOR: blue">type </SPAN><FONT color=#000000>WorkerRole() =
    </FONT><SPAN style="COLOR: blue">inherit </SPAN><FONT color=#000000>RoleEntryPoint()

    </FONT><SPAN style="COLOR: green">// The page to start crawling from
    </SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>startpage = </FONT><SPAN style="COLOR: maroon">@"https://blogs.msdn.com/lukeh"
    </SPAN><SPAN style="COLOR: green">// The filter to apply to links while crawling
    </SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>pageFilter = </FONT><SPAN style="COLOR: blue">fun </SPAN><FONT color=#000000>(url:string) </FONT><SPAN style="COLOR: blue">-&gt; </SPAN><FONT color=#000000>url.StartsWith(</FONT><SPAN style="COLOR: maroon">"https://blogs.msdn.com/"</SPAN><FONT color=#000000>)

    </FONT><SPAN style="COLOR: green">/// Get the contents of a given url
    </SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>http(url: string) = 
        </FONT><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>req    = WebRequest.Create(url) 
        </FONT><SPAN style="COLOR: blue">use </SPAN><FONT color=#000000>resp   = req.GetResponse()
        </FONT><SPAN style="COLOR: blue">use </SPAN><FONT color=#000000>stream = resp.GetResponseStream() 
        </FONT><SPAN style="COLOR: blue">use </SPAN><FONT color=#000000>reader = </FONT><SPAN style="COLOR: blue">new </SPAN><FONT color=#000000>StreamReader(stream) 
        </FONT><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>html   = reader.ReadToEnd()
        html

    </FONT><SPAN style="COLOR: green">/// Get the links from a page of HTML
    </SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>linkPat = </FONT><SPAN style="COLOR: maroon">"href=\s*\"[^\"h]*(https://[^&amp;\"]*)\""
    </SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>getLinks text =  [ </FONT><SPAN style="COLOR: blue">for </SPAN><FONT color=#000000>m </FONT><SPAN style="COLOR: blue">in </SPAN><FONT color=#000000>Regex.Matches(text,linkPat)  </FONT><SPAN style="COLOR: blue">-&gt; </SPAN><FONT color=#000000>m.Groups.Item(1).Value ]
    
    </FONT><SPAN style="COLOR: green">/// Handle the message msg using the given queue and blob container
    </SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>HandleMessage (msg : Message) (queue : MessageQueue, container: BlobContainer) =
        </FONT><SPAN style="COLOR: green">// There was a new item, get the contents
        </SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>url = msg.ContentAsString();
        </FONT><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>urlBlobName = HttpUtility.UrlEncode(url)
        </FONT><SPAN style="COLOR: green">// Don't get the page if we've already seen it
        </SPAN><SPAN style="COLOR: blue">if </SPAN><FONT color=#000000>not(container.DoesBlobExist(urlBlobName)) 
        </FONT><SPAN style="COLOR: blue">then
            do </SPAN><FONT color=#000000>RoleManager.WriteToLog(</FONT><SPAN style="COLOR: maroon">"Information"</SPAN><FONT color=#000000>, String.Format(</FONT><SPAN style="COLOR: maroon">"Handling new url: '{0}'"</SPAN><FONT color=#000000>, url));
            </FONT><SPAN style="COLOR: blue">try
                </SPAN><SPAN style="COLOR: green">// Get the contents of the page
                </SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>content = http url
                </FONT><SPAN style="COLOR: green">// Store the page into the blob store
                </SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>props = </FONT><SPAN style="COLOR: blue">new </SPAN><FONT color=#000000>BlobProperties(urlBlobName)
                </FONT><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>_ = container.CreateBlob(props, </FONT><SPAN style="COLOR: blue">new </SPAN><FONT color=#000000>BlobContents(System.Text.UTF8Encoding.Default.GetBytes(content)), </FONT><SPAN style="COLOR: blue">true</SPAN><FONT color=#000000>);
                
                </FONT><SPAN style="COLOR: green">// Get the links from the page
                </SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>links = getLinks content
                
                </FONT><SPAN style="COLOR: green">// Filter down the links and then create a new work item for each
                </SPAN><FONT color=#000000>links
                |&gt; Seq.filter pageFilter
                |&gt; Seq.distinct
                |&gt; Seq.filter (</FONT><SPAN style="COLOR: blue">fun </SPAN><FONT color=#000000>link </FONT><SPAN style="COLOR: blue">-&gt; </SPAN><FONT color=#000000>not(container.DoesBlobExist(HttpUtility.UrlEncode(link))))
                |&gt; Seq.iter (</FONT><SPAN style="COLOR: blue">fun </SPAN><FONT color=#000000>link </FONT><SPAN style="COLOR: blue">-&gt; </SPAN><FONT color=#000000>queue.PutMessage(</FONT><SPAN style="COLOR: blue">new </SPAN><FONT color=#000000>Message(link)) |&gt; ignore)
                queue.DeleteMessage(msg) |&gt; ignore
            </FONT><SPAN style="COLOR: blue">with
            </SPAN><FONT color=#000000>| _ </FONT><SPAN style="COLOR: blue">-&gt;</SPAN><FONT color=#000000>()
    
    </FONT><SPAN style="COLOR: green">/// Main loop of worker process
    </SPAN><SPAN style="COLOR: blue">let rec </SPAN><FONT color=#000000>Loop (queue : MessageQueue, container: BlobContainer) = 
        </FONT><SPAN style="COLOR: green">// Get the next page to crawl from the queue
        </SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>msg = queue.GetMessage(240);
        </FONT><SPAN style="COLOR: blue">if </SPAN><FONT color=#000000>msg = </FONT><SPAN style="COLOR: blue">null
        then </SPAN><FONT color=#000000>Thread.Sleep(1000)
        </FONT><SPAN style="COLOR: blue">else </SPAN><FONT color=#000000>HandleMessage msg (queue, container)
        Loop(queue,container)
    
    </FONT><SPAN style="COLOR: blue">override </SPAN><FONT color=#000000>wp.Start() =
        </FONT><SPAN style="COLOR: green">// Initialize the Blob storage
        </SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>blobStorage = BlobStorage.Create(StorageAccountInfo.GetDefaultBlobStorageAccountFromConfiguration());
        </FONT><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>container = blobStorage.GetBlobContainer(</FONT><SPAN style="COLOR: maroon">"searchengine"</SPAN><FONT color=#000000>);
        </FONT><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>a = container.CreateContainer(</FONT><SPAN style="COLOR: blue">null</SPAN><FONT color=#000000>, ContainerAccessControl.Public);

        </FONT><SPAN style="COLOR: green">// Initialize the Queue storage
        </SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>queueStorage = QueueStorage.Create(StorageAccountInfo.GetDefaultQueueStorageAccountFromConfiguration());
        </FONT><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>queue = queueStorage.GetQueue(</FONT><SPAN style="COLOR: maroon">"searchworker"</SPAN><FONT color=#000000>);
        </FONT><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>b = queue.CreateQueue()
        
        </FONT><SPAN style="COLOR: green">// Put an initial message in the queue, using the start page
        </SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>c = queue.PutMessage(</FONT><SPAN style="COLOR: blue">new </SPAN><FONT color=#000000>Message(startpage));
        
        </FONT><SPAN style="COLOR: green">// Begin the main loop, processing messages in the queue
        </SPAN><FONT color=#000000>Loop(queue, container)
        
    </FONT><SPAN style="COLOR: blue">override </SPAN><FONT color=#000000>wp.GetHealthStatus() = RoleStatus.Healthy</FONT>&nbsp;</SPAN></PRE>
<P><A href="https://11011.net/software/vspaste" mce_href="https://11011.net/software/vspaste"></A></P>
<H5>Worker Roles</H5>
<P>The code above defines the implementation of a Worker Role – a process which runs in the background, waiting for work to do, and then processing these work requests.&nbsp; The worker role is set to run 4 instance simultaneously, which means that there will be 4 instances of this worker processing work items as they come in.&nbsp; This gives an implicit parallelism – in fact, the initial release of Azure will run one process per core, so you really are getting effective parallelism this way.&nbsp; Notice also that this requires that the worker processes are inherently stateless.&nbsp; Both aspects make typical functional design approaches that are common in F# natural for developing these worker roles.</P>
<H5>Queues and Blobs</H5>
<P>This sample uses two of the three data formats supported by Windows Azure.&nbsp; The queue storage holds the work items. The blob storage holds the pages visited during the web crawl.&nbsp; When an instance of the worker role Starts, it connects to the blob store and the queue store, then puts an initial work item in the queue and goes into a loop processing work items out of the queue.</P>
<H2>Conclusion</H2>Ideas for any other interesting F# applications on Windows Azure?&nbsp; Download the <A href="https://code.msdn.microsoft.com/fsharpazure" mce_href="https://code.msdn.microsoft.com/fsharpazure">templates and samples</A>.]]></content:encoded>
    </item>
    <item>
      <title>Standard Deviation and Event-based Programming</title>
      <link>https://docs.microsoft.com/archive/blogs/lukeh/standard-deviation-and-event-based-programming</link>
      <pubDate>Fri, 10 Oct 2008 11:47:00 GMT</pubDate>
      <dc:creator><![CDATA[Luke Hoban [MS]]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/lukeh/2008/10/10/standard-deviation-and-event-based-programming/</guid>
      <description><![CDATA[A couple weeks ago, I had the opportunity to do a really fun presentation on F# at the .NET Meetup...]]></description>
      <content:encoded><![CDATA[<P>A couple weeks ago, I had the opportunity to do a really fun presentation on F# at the <A href="https://dotnet.meetup.com/120/calendar/8580054/?a=cr1p_grp" mce_href="https://dotnet.meetup.com/120/calendar/8580054/?a=cr1p_grp">.NET Meetup</A> in New York.&nbsp; At the end, I got a great question, which I talked about a little at the presentation, but thought I’d talk about further in a blog post.</P>
<P>The following isn’t exactly how the conversation went - but roughly captures what we talked about, and covers a lot of fun F# topics.&nbsp; There’s some allusions here to ideas from statistics, time-series analysis, <A href="https://en.wikipedia.org/wiki/Complex_event_processing" mce_href="https://en.wikipedia.org/wiki/Complex_event_processing">CEP</A> and <A href="https://en.wikipedia.org/wiki/Functional_reactive_programming" mce_href="https://en.wikipedia.org/wiki/Functional_reactive_programming">FRP</A>.</P>
<H3>“How would you compute standard deviation over a stream of data in F#?”</H3>
<P><A href="https://en.wikipedia.org/wiki/Standard_deviation" mce_href="https://en.wikipedia.org/wiki/Standard_deviation">Standard deviation</A> is a pretty straightforward computation with F#.&nbsp; There’s a few ways to write it, but with “average” and “averageBy” built-in, they provide a particularly simple option. </P><PRE class=code><SPAN style="COLOR: green"><SPAN style="COLOR: green">/// Square a number
</SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>sqr x = x * x

</FONT><SPAN style="COLOR: green">/// Compute the standard deviation of a list of numbers
</SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>stddev nums = 
    </FONT><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>mean = nums |&gt; List.average
    </FONT><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>variance = nums |&gt; List.averageBy (</FONT><SPAN style="COLOR: blue">fun </SPAN><FONT color=#000000>x </FONT><SPAN style="COLOR: blue">-&gt; </SPAN><FONT color=#000000>sqr(x - mean))
    sqrt(variance)</FONT></SPAN></PRE>
<H3>“Okay – but what if I want the inputs to be long, potentially infinite sources of data?”</H3>
<P>The previous function worked over lists.&nbsp; We can change it to work over sequences (IEnumerables) instead.&nbsp; Pleasantly, it’s basically the same code.&nbsp; But the result of working over sequences is that this function will work with any sort of data.&nbsp; It could be a sequence of numbers that result from a LINQ to SQL query, it could be a sequence of numbers read lazily from a very long file, etc.&nbsp; </P><PRE class=code><SPAN style="COLOR: green">/// Compute the standard deviation of a sequence of numbers
</SPAN><SPAN style="COLOR: blue">let </SPAN>stddevSeq numSeq = 
    <SPAN style="COLOR: blue">let </SPAN>mean = 
        numSeq |&gt; Seq.average
    <SPAN style="COLOR: blue">let </SPAN>variance = 
        numSeq |&gt; Seq.averageBy (<SPAN style="COLOR: blue">fun </SPAN>x <SPAN style="COLOR: blue">-&gt; </SPAN>sqr(x - mean))
    sqrt(variance)</PRE><A href="https://11011.net/software/vspaste" mce_href="https://11011.net/software/vspaste"></A>
<H3>“That’s computing what I want, but can I get all the partial results as my stream of data is processed? ”</H3>
<P>This makes things more interesting.&nbsp; Instead of just computing the standard deviation, we really want to do an “online” calculation, where we compute enough information so that as each new datapoint comes in, we can easily produce the new standard deviation.&nbsp; This is a different algorithmic approach to the same mathematical formula.&nbsp; Luckily, wikipedia has what we need- an <A href="https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance" mce_href="https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance">on-line algorithm for standard deviation</A> from Knuth.</P><PRE class=code><SPAN style="COLOR: green">/// Compute the running mean and standard deviation
/// over a sequence of numbers
</SPAN><SPAN style="COLOR: blue">let </SPAN>meanAndStdDev nums = 
    <SPAN style="COLOR: green">// A function which updates the on-line computation of 
    // n, mean and M2 given a new datapoint x
    </SPAN><SPAN style="COLOR: blue">let </SPAN>newValues (n, mean, M2) x = 
        <SPAN style="COLOR: blue">let </SPAN>n' = n+1.
        <SPAN style="COLOR: blue">let </SPAN>delta = x - mean
        <SPAN style="COLOR: blue">let </SPAN>mean' = mean + delta/n'
        <SPAN style="COLOR: blue">let </SPAN>M2' = M2 + delta*(x - mean')
        (n', mean', M2')
    <SPAN style="COLOR: green">// The initial vaues of n, mean and M2
    </SPAN><SPAN style="COLOR: blue">let </SPAN>startValues = (0., 0., 0.)
    <SPAN style="COLOR: green">// The resulting event stream is a scan over the input events 
    </SPAN>nums 
    |&gt; Seq.scan newValues startValues
    |&gt; Seq.map (<SPAN style="COLOR: blue">fun </SPAN>(n, mean, M2) <SPAN style="COLOR: blue">-&gt; </SPAN>(mean, sqrt(M2/(n))))</PRE>
<P>This time the code has a few interesting features:</P>
<OL>
<LI>A local function “newValues” updates n, mean and M2 based on old values and a new datapoint x.&nbsp; Notice that (a) this is strikingly similar to the pseudo-code in the <A href="https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance" mce_href="https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance">wikipedia</A> article but (b) this is a functional implementation, so instead of changing the values, we just compute new ones.</LI>
<LI>The function “Seq.scan” takes care of the heavy lifting.&nbsp; This function, and the related “fold” and “reduce” can be used to capture many common design patterns seen in “<A href="https://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!511.entry" mce_href="https://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!511.entry">programming in the small</A>”.&nbsp; Scan walks across an input collection applying a function to it’s current accumulator argument, and returning a collection of the results that it builds up as it goes.&nbsp; If you’ve haven’t written code using these before, they can feel uncomfortable at first, but after you’ve used each of these once or twice, you’ll notice them as common patterns that you are currently encoding as for loops, if statements and local state in your programs.&nbsp; “scan” and it’s related functions give us the ability to name that design pattern and then re-use it – resulting in more declarative code.</LI></OL>
<H3>“Perfect!&nbsp; But my actual stream of data (stock ticker prices) is long running, and will provide new data points periodically over minutes, days and weeks.”</H3>
<P>Another fun twist on the problem!&nbsp; Sequences (IEnumerables) have the property that the producer of the data offers up a way to ask for more, and the consumer is in charge of pulling it out.&nbsp; While it’s doing so, it’s busy the whole time, so if the producer&nbsp; doesn’t have the data yet, it will have to block waiting for it to be available.&nbsp; This is not what you want in the long running case, where instead we want to think about the data stream as a sequence of <B>events</B>.&nbsp; With events, the consumer offers up a way to deal with new data whenever it’s available, and the producer is in charge of pushing the new data points out.&nbsp; For the same reasons that there is so much interest in smart phones with push email, we should all want our long-running data streams to be event based instead of sequence based.</P><PRE class=code><PRE class=code><SPAN style="COLOR: blue">let </SPAN>boundedMouseMax = 
    form.MouseMove 
    |&gt; Event.filter (<SPAN style="COLOR: blue">fun </SPAN>mea <SPAN style="COLOR: blue">-&gt; </SPAN>mea.X &gt; 10 &amp;&amp; mea.Y &gt; 10 &amp;&amp; mea.X &lt; 90 &amp;&amp; mea.Y &lt; 90)
    |&gt; Event.map (<SPAN style="COLOR: blue">fun </SPAN>mea <SPAN style="COLOR: blue">-&gt; </SPAN>max mea.X mea.Y)</PRE><PRE class=code>&nbsp;</PRE><PRE class=code><SPAN style="COLOR: blue">do </SPAN>boundedMouseMax |&gt; Event.add (<SPAN style="COLOR: blue">fun </SPAN>maxCoord <SPAN style="COLOR: blue">-&gt; </SPAN>printfn <SPAN style="COLOR: maroon">"max is: %A" </SPAN>maxCoord)</PRE></PRE>
<P>Events in F# are just standard .NET events.&nbsp; But F# allows you to program with these events in a “first-class” way, meaning you can pass them around as data, and there are functions in the “Event” module for taking events and generating new events from them.&nbsp; For instance, we could take a mouse move event and call “Event.filter” to filter out any time it is outside a bounding box, then “Event.map” to pick the larger of the X or Y coordinate of the mouse.&nbsp; The result is then a new event which will fire only when the mouse is in the bounding box, and will produce the larger of it’s X and Y coordinate as it’s value. We can then hook up a listener to print out the values whenever this new event fires.</P>
<P>But how do we use this to solve the original problem? </P><PRE class=code><SPAN style="COLOR: green">/// Compute a running mean and standard deviation over the 
/// input event stream of floating point numbers
</SPAN><SPAN style="COLOR: blue">let </SPAN>meanAndStdDev nums = 
    <SPAN style="COLOR: green">// A function which updates the on-line computation of n, mean and M2
    </SPAN><SPAN style="COLOR: blue">let </SPAN>newValues (n, mean, M2) x = 
        <SPAN style="COLOR: blue">let </SPAN>n' = n+1.
        <SPAN style="COLOR: blue">let </SPAN>delta = x - mean
        <SPAN style="COLOR: blue">let </SPAN>mean' = mean + delta/n'
        <SPAN style="COLOR: blue">let </SPAN>M2' = M2 + delta*(x - mean')
        (n', mean', M2')
    <SPAN style="COLOR: green">// The initial vaues of n, mean and M2
    </SPAN><SPAN style="COLOR: blue">let </SPAN>startValues = (0., 0., 0.)
    <SPAN style="COLOR: green">// The resulting event stream is a scan over the input events 
    </SPAN>nums 
    |&gt; Event.scan newValues startValues
    |&gt; Event.map (<SPAN style="COLOR: blue">fun </SPAN>(n, mean, M2) <SPAN style="COLOR: blue">-&gt; </SPAN>(mean, sqrt(M2/(n))))</PRE>
<P>It’s almost identical to the “on-line” algorithm over sequences! This is one of the important benefits of writing more declarative code using constructs like “scan”.&nbsp; Although the implementations of “scan” over sequences and over events are quite different under the hood – the design pattern of scanning makes sense over both, and is the concept we can program with to tackle the problem at a higher-level.&nbsp; It really makes you feel that we’ve succeeded in expressing the “what” in place of the “how”. </P>
<P>Here’s what it looks like to use this new function we’ve created:</P><PRE class=code><SPAN style="COLOR: green"><SPAN style="COLOR: green">// Create a new event – we would hook up to the stock ticker events if they were available
</SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>numEvent = </FONT><SPAN style="COLOR: blue">new </SPAN><FONT color=#000000>Event&lt;float&gt;()
</FONT><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>numEventStream, fireNewNum = numEvent.Publish, numEvent.Trigger

</FONT><SPAN style="COLOR: green">// Derive a new event that computes the running mean and stddev 
// over the original event stream
</SPAN><SPAN style="COLOR: blue">let </SPAN><FONT color=#000000>stddevEvents = meanAndStdDev numEventStream

</FONT><SPAN style="COLOR: green">// Hook up an event handler to print out the new mean and standard deviation 
</SPAN><SPAN style="COLOR: blue">do </SPAN><FONT color=#000000>stddevEvents |&gt; Event.add (</FONT><SPAN style="COLOR: blue">fun </SPAN><FONT color=#000000>(mean, stddev) </FONT><SPAN style="COLOR: blue">-&gt; </SPAN><FONT color=#000000>printfn </FONT><SPAN style="COLOR: maroon">"Mean = %A, StdDev = %A" </SPAN><FONT color=#000000>mean stddev)

</FONT><SPAN style="COLOR: blue">do </SPAN><FONT color=#000000>fireNewNum 3.
</FONT><SPAN style="COLOR: blue">do </SPAN><FONT color=#000000>fireNewNum 7.
</FONT><SPAN style="COLOR: blue">do </SPAN><FONT color=#000000>fireNewNum 7.
</FONT><SPAN style="COLOR: blue">do </SPAN><FONT color=#000000>fireNewNum 19.</FONT></SPAN></PRE>
<H2>Conclusion</H2>
<P>This is a fun example that really shows off why it’s so valuable to use higher-level design patterns for programming in the small – like “map”, “average”, “averageBy” and “scan”.&nbsp; First class events in F# are a unifying features which allows you to do the same kind of programming you use with sequences and apply it also to events.&nbsp; This is really compelling, because it’s a case where two data sources which are conceptually very similar are often programmed in very different ways – but with higher-level programming models that functional programming and F# provide, you can program against both using the same techniques.</P>]]></content:encoded>
    </item>
    <item>
      <title>F# September 2008 CTP - Known Issues</title>
      <link>https://docs.microsoft.com/archive/blogs/lukeh/f-september-2008-ctp-known-issues</link>
      <pubDate>Wed, 17 Sep 2008 09:48:00 GMT</pubDate>
      <dc:creator><![CDATA[Luke Hoban [MS]]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/lukeh/2008/09/17/f-september-2008-ctp-known-issues/</guid>
      <description><![CDATA[We released the F# CTP a few weeks ago, and have been receiving tons of great feedback from F#...]]></description>
      <content:encoded><![CDATA[<p>We released the F# CTP a few weeks ago, and have been receiving tons of great feedback from F# developers since.&nbsp; Here are some of the common issues which we've been asked about.&nbsp; We'll continue to add on to this list as any new issues are raised.&nbsp; Please continue to send any feedback, suggestions or comments to us at <a mce_href="mailto:fsbugs@microsoft.com" href="mailto:fsbugs@microsoft.com">fsbugs@microsoft.com</a>.</p><h1>Known Issues </h1><ol><li><a href="https://blogs.msdn.com/controlpanel/blogs/posteditor.aspx?SelectedNavItem=Posts&amp;sectionid=3786&amp;postid=8955796#1">Ctrl+. keybinding doesn't invoke View.ShowSmartTag in C# and VB editors</a> </li><li><a href="https://blogs.msdn.com/controlpanel/blogs/posteditor.aspx?SelectedNavItem=Posts&amp;sectionid=3786&amp;postid=8955796#2">Saving an F# project can fail when 'Save As' is invoked or VB profile is used </a></li><li><a href="https://blogs.msdn.com/controlpanel/blogs/posteditor.aspx?SelectedNavItem=Posts&amp;sectionid=3786&amp;postid=8955796#3">Cannot add a reference to a project in a Solution folder</a> </li><li><a href="https://blogs.msdn.com/controlpanel/blogs/posteditor.aspx?SelectedNavItem=Posts&amp;sectionid=3786&amp;postid=8955796#4">Cannot add reference from an F# project to a C++/CLI project in Visual Studio</a> </li><li><a href="https://blogs.msdn.com/controlpanel/blogs/posteditor.aspx?SelectedNavItem=Posts&amp;sectionid=3786&amp;postid=8955796#5">Error message about a missing reference may get 'stuck' in the Error List&nbsp; </a></li><li><a href="https://blogs.msdn.com/controlpanel/blogs/posteditor.aspx?SelectedNavItem=Posts&amp;sectionid=3786&amp;postid=8955796#6">F# on 64bit</a> </li><li><a href="https://blogs.msdn.com/controlpanel/blogs/posteditor.aspx?SelectedNavItem=Posts&amp;sectionid=3786&amp;postid=8955796#7">Build errors are not reported in the Error List</a> </li><li><a href="https://blogs.msdn.com/controlpanel/blogs/posteditor.aspx?SelectedNavItem=Posts&amp;sectionid=3786&amp;postid=8955796#8">Dynamically evaluating a quotation which uses the "pown" function fails at runtime</a> </li></ol><h2><a title="1" name="1" class=""></a>1. Ctrl+. keybinding doesn't invoke View.ShowSmartTag in C# and VB editors</h2><p><i><b>Issue</b></i>: </p><p>The F# CTP uses the ctrl+. keybinding to break execution in the F# Interactive.&nbsp; However, this keybinding is incorrectly applied globally, which prevents it from working in it's standard Visual Studio use of activating an editor SmartTag in the C# and VB editors.&nbsp; The result is that installing the F# CTP prevents this keybinding from working in the C# and VB editors.</p><p><i><b>Workaround</b></i>:&nbsp; </p><p>To set the keybinding for ctrl+. back to it's original binding to the SmartTag, do the following. <br>In Tools-&gt;Options-&gt;Environment-&gt;Keyboard do the following: <br>1) Type "View.ShowSmartTag" in the "Show commands containing:" entry field <br>2) Hold down "ctrl" and press "." (dot) in the "Press shortcut keys" entry field <br>3) Click "Assign" </p><p>You can optionally re-assign the "OtherContextMenus.FSIConsoleContext.CancelEvaluation" command another keybinding, using similar steps.&nbsp; Alternatively you can use the right-click menu option to cancel evaluation in the F# Interactive when needed.</p><h2><a title="2" name="2" class=""></a>2. Saving an F# project can fail when 'Save As' is invoked or VB profile is used</h2><p><b><i>Issue</i></b>:</p><p>The 'Save As' command in Visual Studio does not work on F# project files in the CTP release.&nbsp; Projects can be saved with the name they were created with, but cannot be saved with a different name.&nbsp; Related to this, if the 'Save new projects when created' option in Visual Studio is turned off, it is not possible to save an F# project after creating it.&nbsp; Note that this setting is off by default in the VB profile, but on in all other Visual Studio profiles.&nbsp; In both cases, an error message saying "The operation could not be completed.&nbsp; No such interface supported" will be raised.</p><p><b><i>Workaround</i></b>:</p><p>In Tools-&gt;Options-&gt;Projects and Solutions-&gt;General ensure that 'Save new projects when created' is checked.&nbsp; To move a project file to another location, save the project and close Visual Studio, then move the project file manually and then reopen it in it's new location.</p><h2><a title="3" name="3" class=""></a>3. Cannot add a reference to a project in a Solution folder</h2><p><b><i>Issue</i></b>: </p><p mce_keep="true">&nbsp;</p><p>Attempting to add a reference from an F# project to a project which is inside a Solution Folder results in "Object not set to an instance of an object." error message, and fails to add the reference.</p><p><b><i>Workaround</i></b>:</p><p>You can add an assembly reference to the output of the other project's build by browsing to the assembly in the Add Reference... dialog.&nbsp; In some cases, it may be important to pick up the correct version of the referenced assembly depending on the build configuration, in these cases, rules such as the following can be added manually to the .fsproj file:</p><p>&nbsp;&nbsp;&nbsp; &lt;Reference Include="..\SolutionFolder\Library2\bin\Debug\Library2.dll" Condition ="'$(Configuration)' == 'Debug'" /&gt; </p><p>&nbsp;&nbsp;&nbsp; &lt;Reference Include="..\SolutionFolder\Library2\bin\Release\Library2.dll" Condition ="'$(Configuration)' == 'Release'" /&gt;</p><h2><a title="4" name="4" class=""></a>4. Cannot add reference from an F# project to a C++/CLI project in Visual Studio</h2><p><i><b>Issue</b></i>:&nbsp; </p><p>Attempting to add a project reference from an F# project to a C++/CLI project results in "Object not set to an instance of an object." error message, and fails to add the reference.</p><p><i><b>Workaround</b></i>:&nbsp; </p><p>You can add an assembly reference to the output of the C++/CLI build by browsing to the assembly in the Add Reference... dialog.&nbsp; In some cases, it may be important to pick up the correct version of the referenced assembly depending on the build configuration, in these cases, rules such as the following can be added manually to the .fsproj file:</p><p>&nbsp;&nbsp;&nbsp; &lt;Reference Include="..\ClassLibrary2\bin\Debug\ClassLibrary2.dll" Condition ="'$(Configuration)' == 'Debug'" /&gt; </p><p>&nbsp;&nbsp;&nbsp; &lt;Reference Include="..\ClassLibrary2\bin\Release\ClassLibrary2.dll" Condition ="'$(Configuration)' == 'Release'" /&gt;</p><h2>5. Error message about a missing reference may get 'stuck' in the Error List</h2><p><i><b>Issue</b></i>:&nbsp; </p><p>Adding a project reference to a project which has never been built will result in an error message appearing in the referencing project.&nbsp; This error message may not go away when the referenced project is built.</p><p><i><b>Workaround</b></i>:&nbsp; </p><p>Shutting down and restarting Visual Studio will cause the error message to go away.&nbsp;&nbsp; </p><h2><a title="6" name="6" class=""></a>6. F# on 64bit</h2><p><i><b>Issue</b></i>:&nbsp; </p><p>Broadly speaking, F# applications will work well on 64bit machines and operating systems.&nbsp; However, there are two possible issues to be aware of.</p><ol><li>The F# compiler and interactive are both 32bit processes, and will run in the WoW64 on 64-bit operating systems.&nbsp; This may prevent loading native 64bit code into the F# interactive and may cause registry reads/writes to behave differently than in a true 64bit process.&nbsp; </li><li>F# code may be compiled as either 32bit, 64bit, or platform agnostic (AnyCPU).&nbsp; Note that when F# applications are run on 64bit, they use the CLR's 64bit Just-In-Time compiler, which may not do tail call optimization in all cases, possibly resulting in StackOverflowExceptions in 64bit environments that were not seen in 32bit environments. </li></ol><p><i><b>Workaround</b></i>:&nbsp; </p><p>It is possible to make F# Interactive load as 64-bit by modifying fsi.exe using corflags.exe. There are details on this .NEt Framework SDK tool at <a href="https://msdn.microsoft.com/en-us/library/ms164699(VS.80).aspx">https://msdn.microsoft.com/en-us/library/ms164699(VS.80).aspx</a>.</p><h2><a title="7" name="7" class=""></a>7. Build errors are not reported in the Error List</h2><p><i><b>Issue</b></i>:&nbsp; </p><p>The error list in Visual Studio shows errors reported by the F# background compiler, but does not show errors reported by the F# compiler during an explicit build.&nbsp; These are in most cases the same, so that this is not always an issue.&nbsp; However, if some files in the project are not open, or if an error is reported during generation of the assembly, it may not appear in the error list.&nbsp; Additionally, errors will appear in the error list for any open files, even ones which are not part of the current project.</p><p><i><b>Workaround</b></i>:&nbsp; </p><p>The Output Window in Visual Studio will always show the full results of a build.</p><h2><a title="8" name="8" class=""></a>8. Dynamically evaluating a quotation which uses the "pown" function fails at runtime</h2><p><i><b>Issue</b></i>: </p><p>Attempting to use the LINQ evaluation of a quotation involving the "pown" function will result in a DynamicInvocationNotSupportedException.</p><p><i><b>Workaround</b></i>: </p><p>Consider using the ** exponentiation operator, a custom integer exponentiation function or repeated multiplication instead.</p>]]></content:encoded>
    </item>
    <item>
      <title>ICFP Programming Contest</title>
      <link>https://docs.microsoft.com/archive/blogs/lukeh/icfp-programming-contest</link>
      <pubDate>Thu, 10 Jul 2008 00:37:00 GMT</pubDate>
      <dc:creator><![CDATA[Luke Hoban [MS]]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/lukeh/2008/07/10/icfp-programming-contest/</guid>
      <description><![CDATA[This years'&nbsp;installment of the ICFP Programming Contest is coming up this weekend.&nbsp; For...]]></description>
      <content:encoded><![CDATA[<P>This years'&nbsp;installment of the <A href="https://blogs.msdn.com/lukeh/archive/2008/05/05/huffman-coding-with-f.aspx" mce_href="https://blogs.msdn.com/lukeh/archive/2008/05/05/huffman-coding-with-f.aspx">ICFP Programming Contest</A> is coming up this weekend.&nbsp; For those who haven't had the chance to try out this programming contest before, I definitely recommend it.&nbsp; I've done the contest 3 of the last 5 years, and each time has been an amazing experience.&nbsp; This year, we've got a couple of teams here who'll be doing the contest, and we're excited to see what the organizers have in store.&nbsp; </P>
<P>The task for the contest changes quite a bit each year, but tends to incorporate themese like implementing interpreters/compilers for simple languages/runtimes and solving optimization or state-space exploration problems related to these interperpreters or programs written to run on these interpreters.&nbsp; In each of the last two years' contests, some really fun puzzle elements have been incoporated into the contest, along with richer storytelling.</P>
<H4>"Universal Machine" in F#</H4>
<P>Of the years I've done the ICFP programming contest, my favorite so far has been the <A href="https://boundvariable.org/" mce_href="https://boundvariable.org/">2006 contest</A>.&nbsp; It was truly an inspired creation, and I am rather in awe of the group from CMU who put it together.&nbsp; If you didn't do the contest in 2006, you can still go back to the site and try it out - which I can definitely recommend.</P>
<P>The contest <A href="https://boundvariable.org/task.shtml" mce_href="https://boundvariable.org/task.shtml">started</A> seemingly simply - pointing to a <A href="https://boundvariable.org/um-spec.txt" mce_href="https://boundvariable.org/um-spec.txt">spec for a virtual machine</A> (the "UM"), a <A href="https://boundvariable.org/codex.umz" mce_href="https://boundvariable.org/codex.umz">binary</A> to run on the virtual machine (the "Codex") and a "decryption key" to use: '(\b.bb)(\v.vv)06FHPVboundvarHRAk'.&nbsp; </P>
<P>Earlier this week, to re-live some of the fun of the 2006 contest, and to get mentally ready for this years contest, I re-implemented the UM, this time in F#.&nbsp; Here's what it looks like (take a look at the spec linked above for an expalanation of what it's doing):</P><PRE class=code><SPAN style="COLOR: rgb(0,0,255)">open</SPAN> System<SPAN style="COLOR: rgb(0,0,255)">
open</SPAN> System.IO<SPAN style="COLOR: rgb(0,0,255)">

type</SPAN> UM(p0 : byte[], input : Stream,  output : Stream) = 

    <SPAN style="COLOR: rgb(0,128,0)">// Read byte[] in as little-endian uint[]</SPAN>
    <SPAN style="COLOR: rgb(0,0,255)">let</SPAN> p0AsUInts =
        [| <SPAN style="COLOR: rgb(0,0,255)">for</SPAN> i <SPAN style="COLOR: rgb(0,0,255)">in</SPAN> 0..4..(p0.Length-4) <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN>
            ((uint32 p0.[i])&lt;&lt;&lt;24) + 
            ((uint32 p0.[i+1])&lt;&lt;&lt;16) + 
            ((uint32 p0.[i+2])&lt;&lt;&lt;8) + 
            ((uint32 p0.[i+3])) |]
    <SPAN style="COLOR: rgb(0,128,0)">// The resizable array of memory pages starts with just the input</SPAN>
    <SPAN style="COLOR: rgb(0,0,255)">let</SPAN> mem = ResizeArray.create 1 p0AsUInts
    <SPAN style="COLOR: rgb(0,128,0)">// The registers are initialized to 0</SPAN>
    <SPAN style="COLOR: rgb(0,0,255)">let</SPAN> reg = [|0u;0u;0u;0u;0u;0u;0u;0u|]

    <SPAN style="COLOR: rgb(0,128,0)">// The main loop of the interpreter.  Should be *fast*.</SPAN>
    <SPAN style="COLOR: rgb(0,0,255)">let</SPAN> <SPAN style="COLOR: rgb(0,0,255)">rec</SPAN> cycle finger =
        <SPAN style="COLOR: rgb(0,0,255)">let</SPAN> arr = mem.[0]
        <SPAN style="COLOR: rgb(0,0,255)">let</SPAN> op = arr.[finger]
        <SPAN style="COLOR: rgb(0,0,255)">let</SPAN> code = op &gt;&gt;&gt; 28
        <SPAN style="COLOR: rgb(0,0,255)">let</SPAN> (a,b,c) = (int ((op &gt;&gt;&gt; 6) &amp;&amp;&amp; 0b111u), int ((op &gt;&gt;&gt; 3) &amp;&amp;&amp; 0b111u), int ((op) &amp;&amp;&amp; 0b111u))
        <SPAN style="COLOR: rgb(0,0,255)">let</SPAN> (a2, value) = (int (op &gt;&gt;&gt; 25) &amp;&amp;&amp; 0b111, op &amp;&amp;&amp; 0b1111111111111111111111111u)
        <SPAN style="COLOR: rgb(0,0,255)">match</SPAN> code <SPAN style="COLOR: rgb(0,0,255)">with</SPAN>
        | 0u <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> (<SPAN style="COLOR: rgb(0,0,255)">if</SPAN> reg.[c] &lt;&gt; 0u <SPAN style="COLOR: rgb(0,0,255)">then</SPAN> reg.[a] &lt;- reg.[b]); cycle (finger+1)
        | 1u <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> (reg.[a] &lt;- mem.[int reg.[b]].[int reg.[c]]); cycle (finger+1)
        | 2u <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> (mem.[int reg.[a]].[int reg.[b]] &lt;- reg.[c]); cycle (finger+1)
        | 3u <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> (reg.[a] &lt;- reg.[b] + reg.[c]); cycle (finger+1)
        | 4u <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> (reg.[a] &lt;- reg.[b] * reg.[c]); cycle (finger+1)
        | 5u <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> (reg.[a] &lt;- reg.[b] / reg.[c]); cycle (finger+1)
        | 6u <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> (reg.[a] &lt;- ~~~ (reg.[b] &amp;&amp;&amp; reg.[c])); cycle (finger+1)
        | 7u <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> ()
        | 8u <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> (mem.Add(Array.zeroCreate (int reg.[c])); reg.[b] &lt;- uint32 (mem.Count - 1)); cycle (finger+1)
        | 9u <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> (mem.[int reg.[c]] &lt;- [||]); cycle (finger+1)
        | 10u <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> (output.WriteByte(byte reg.[c])); cycle (finger+1)
        | 11u <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> (reg.[c] &lt;- uint32 (input.ReadByte() % 255)); cycle (finger+1)
        | 12u <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> (<SPAN style="COLOR: rgb(0,0,255)">if</SPAN> reg.[b] &lt;&gt; 0u <SPAN style="COLOR: rgb(0,0,255)">then</SPAN> mem.[0] &lt;- Array.copy mem.[int reg.[b]]); cycle (int reg.[c])
        | 13u <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> (reg.[a2] &lt;- value); cycle (finger+1)
        | _ <SPAN style="COLOR: rgb(0,0,255)">-&gt;</SPAN> failwith <SPAN style="COLOR: rgb(163,21,21)">"Did not understand %A"</SPAN> (op, code, a, b, c)

    <SPAN style="COLOR: rgb(0,128,0)">/// Start the Universal Machine running</SPAN>
    <SPAN style="COLOR: rgb(0,0,255)">member</SPAN> this.Run() =
        cycle 0<SPAN style="COLOR: rgb(0,0,255)">

let</SPAN> program = File.ReadAllBytes(<SPAN style="COLOR: rgb(163,21,21)">"codex.umz"</SPAN>);<SPAN style="COLOR: rgb(0,0,255)">
let</SPAN> ee = UM(program, Console.OpenStandardInput(), Console.OpenStandardOutput())<SPAN style="COLOR: rgb(0,128,0)">

//Try the following if too much is printed to the screen 
//let ee = UM(program, Console.OpenStandardInput(), new FileStream("umix.um", FileMode.Create))</SPAN>ee.Run()

</PRE><A href="https://11011.net/software/vspaste" mce_href="https://11011.net/software/vspaste"></A>
<H5>Performance</H5>
<P>This code is doing a lot of bit-level operations in F#.&nbsp; The meat of the code is the tight loop that runs executing the "cycle" function.&nbsp; Since this is the runtime that the provided binary will run on, it needs to be fast.&nbsp; And, fortunately,&nbsp;it is.&nbsp; On my laptop, this loop runs about 15million iterations per second.&nbsp; Of course, there are opportunities to improve on the performance of this code, but this turns out to be fast enough for the problem, and it's convenient that you get this performance profile by default.</P>
<P mce_keep="true">&nbsp;</P>
<H5>That Doesn't Look Very Functional?</H5>
<P>This code is not particularly 'functional'.&nbsp; But it is totally reasonable F# code.&nbsp; We often talk about F# as a hybrid functional, imperative and OO programming language.&nbsp; This is an example where the problem domain really suggests the use of some imperative programming ideas.&nbsp; The problem defines some global state: the memory, and the registers.&nbsp; Since we're going to be modifying these constantly during the execution of the runtime, it makes sense to use mutable arrays to store the contents.&nbsp; F# makes this nice and easy to do.</P>
<P mce_keep="true">&nbsp;</P>
<H5>Wrapping it up with a little OO</H5>
<P>As I menionted in a <A href="https://blogs.msdn.com/lukeh/archive/2008/05/05/huffman-coding-with-f.aspx" mce_href="https://blogs.msdn.com/lukeh/archive/2008/05/05/huffman-coding-with-f.aspx">previous blog post</A>, it's really easy to transition between prototyping and component design with F#.&nbsp; The code above wraps up the state and algorithm for the UM in a simple type definition.&nbsp; This provides nice encapsulation and abstraction over the specific binary to run, and the input and output streams to use.&nbsp; And it also wraps up the F# code in a type which could just as easily be consumed from C# or any other .NET langauge. </P>]]></content:encoded>
    </item>
  </channel>
</rss>