All about “F# and You”

Last night at our monthly Tech Valley .NET User Group (TVUG) meeting, we had Rick Minerich come in and do a presentation on F#.  It was a very good presentation.  Rick was enthusiastic and knows F# cold.  One of the cool things that he showed in his presentation were examples in both F# and C#.  It looked like you could replace every 5-10 lines of C# code with F# code.

F# isn’t for everyone, but if you are doing serious number crunching and want to process data in parallel, then you seriously want to look at using F#.  It’s a full fledged member of Visual Studio 2010, it’s not just something bolted on to the architecture.

With F#, asynchronous programming is much simpler.  This useful for performing operations that require asynchronous I/O.  A common example would be collecting data from multiple, non-related web pages.  With F#’s asynchronous workflows, you define a set of operations to be performed in parallel.  The following example from MSDN shows one way that you can implement this.

open System.Net
open Microsoft.FSharp.Control.WebExtensions

let urlList = [ "Microsoft.com", "http://www.microsoft.com/"
"MSDN", "http://msdn.microsoft.com/"
"Bing", "http://www.bing.com"
]

let fetchAsync(name, url:string) =
async {
try
let uri = new System.Uri(url)
let webClient = new WebClient()
let! html = webClient.AsyncDownloadString(uri)
printfn "Read %d characters for %s" html.Length name
with
| ex -> printfn "%s" (ex.Message);
}

let runAll() =
urlList
|> Seq.map fetchAsync
|> Async.Parallel
|> Async.RunSynchronously
|> ignore

runAll()

This code will process each URL in urlList in parallel, and will wait until each sequence has been processed before continuing.  The wait state management and thread housekeeping are handled by F#, the programmer doesn’t have to worry about that at all.

If you want to know more about F#, Rick is a great source.  In addition to his web site, you can find him on Twitter as @Rickasaurus.