F# Hawkeye : Functional Programming

(Harry is @ DevTeach in Vancounver with his family this week. He was hoping to still do Morning Coffee posts, but that’s turned out to be infeasible. So instead, you get a series of pre-written posts about F#.)

If you’re coming from the imperative object-oriented world of C#, Java or VB, functional programming just seems odd at first. But you might as well start getting used to it – functional aspects have been leaking into C# and VB with every version. The way LINQ chains together iterators (Where, Select, Order By, etc) is heavily influenced by FP (aka functional programming).

It takes a while to get the hang of FP, but I’ve found that some problems that are hard to solve in C# are easy in F#. For example, in my parsing code, I have a bunch of boilerplate caching and tracing code that I need to execute in each parsing function. How do I do that in C# without having to cut and paste the boilerplate code over and over again?

In F#, I wrote a function called CacheAndTrace that takes a parsing function as a parameter and returns a new function that adds the caching and tracing code. Since the new function has the same signature as the original parsing function, the caller can’t tell the difference but it saves me having to write the boilerplate code over and over again.

Actually, you can do this type of functional composition with C#. In fact, I first wrote my version of the CacheAndTrace function in C#. But F#’s syntax is much better for functional programming – probably since it was designed for FP, rather than having FP tacked on later.

My father once compared functional programming to Aspect Oriented Programming. AOP is about factoring apart cross cutting concerns, which tends to be hard to do in a straight-up OO language. But in an FP language, AOP-esque separation of concern is fairly straightforward.

F# isn’t a pure functional language – it’s actually a multi-paradigm language, so you can do imperative and OO stuff if you want to. For example, variables are typically immutable in functional programming. So how do you do something like cache the most recent result from a given function – which is what my CacheAndTrace function does? Frankly, I don’t know. But in F#, I can easily mark the cache value as mutable so I can update it on every call. Sort of the best of both worlds, though mixing and matching can get a little tricky.

F#’s OO support is really useful when you interop with other .NET languages, since they’re mostly OO themselves. For example, I’m using NUnit test cases for all my parsing code. My parsing code is F#, so I wanted to write my tests in F# as well. NUnit requires test methods to be grouped into classes known as test fixtures. Frankly, if I were designing a native F# xUnit library, I wouldn’t require all the test methods to be grouped into a class. But it’s easier to just define an test fixture object in F# rather than build my own xUnit Framework for F#

F# as a Second .NET Language

(Harry is @ DevTeach in Vancounver with his family this week. He was hoping to still do Morning Coffee posts, but that’s turned out to be infeasible. So instead, you get a series of pre-written posts about F#.)

I’ve been spending some real quality time with F# of late. I’ve been getting into parsing again, and it turns out that functional pattern matching languages like F# are really good at text processing. After claiming I’d learn F# this year, then abandoning the effort to learn Powershell, I went back to F#. Nothing against PowerShell – I’ve moved over to using it as my primary command line shell and have tricked out my startup script and everything. But I haven’t found much need to code in it lately.

If you’re a .NET ninja guru, you owe it to yourself to take a long look at F#, if for no other reason to expand your mind. It takes a while to get used to. Don Syme (aka father of F#) can attest I’ve been peppering him with questions (Thanks, Don!). I’ve also been writing code in C# and F#, and looking at the result in Reflector so I can understand what’s happening. I certainly am not an F# expert by any stretch, but I do think I’m getting the hang of it.

Since I’ve reached this first plateau of getting it, I thought I’d write out some of the things I like and don’t like about the language. This is by no means an introduction to F#. I’d recommend Robert Pickering’sFoundations of F# book as well as Don’s Expert F# book (when it comes out). You should also be reading Luke Hoban‘s and Jomo Fisher‘s blogs – they both just joined the F# team. C# MVP Tomas Petricek has written several blog posts introducing F#, which he’s brought together in a single post. For an general overview of functional programming (the primary programming paradigm of F#), check out Slava Akhmechet’s Functional Programming For The Rest of Us.

This turned into a fairly long post, so I split it out into a series that I’ll post thru the end of the week.

Update: added link to Tomas Petricek’s F# Introduction

Morning Coffee 120

  • Doing these morning coffee posts is a lot tougher since I cut back my blog reading. Where I used to have no trouble finding 4-5 coffee-worthy items every day, these days I seem to only get 1-2, if that.
  • After starting off 3-0 and 100% on the PK, the Caps dropped four in a row and have been miserable on special teams. The special teams woes continued last night against the Lightning, but they still won. Caps went 0-4 on the powerplay, and coughed up a short handed goal. But they also went 3-3 on the PK, so I guess it wasn’t all bad. Maybe my mother will stop calling for Hanlon’s job now. It’s a long season and as Peerless Prognosticator points out, the rebuild isn’t over.
  • Jomo Fisher, who helped Scott Hanselman auto-merge assemblies, has been digging around in F# of late. As it turns out, he’s joining the F# team so I’m thinking it’s not a huge stretch for him. If you’re a C# developer trying interested in getting a handle on this new F# thing, his blog is a good place to start.
  • Speaking of F#, Don Syme posts about yet another new F# feature: Async Workflows. Workflow is a bad term here IMO since it can be easily confused with WF. Regardless of it’s name, Async Workflows is about making .NET’s Async Programming model a first class citizen in F#. Robert Pickering has a good post explaining how this new feature works.
  • Microsoft sure has a lot of multi-threading / async-programming tools coming out. In addition to F# Async Workflows, there’s the Concurrency and Coordination Runtime, Parallel LINQ and the Task Parallel Library. I would hope all this work eventually coalesces as a coherent product offering.
  • Now that F# is being “producized”, I wonder if the language evolution will slow down. Async workflows were introduced in F# 1.9.2.9. Other recent changes include Computation Expressions (v1.9.2), Use Bindings (v1.9.2) and Active Patterns (v1.9.1). F# seems to churn more in minor releases than C# does in major releases. Of course, that’s because F# was a research project, not a “real” product. Now that it’s going to be a product, will the rate of innovation slow?

Morning Coffee 119

  • The biggest news of the week IMHO is Soma announcing the formation of an F# product team. Specifically, they will “fully integrate the F# language into Visual Studio and continue innovating and evolving F#.” Though Soma calls F# “another first-class programming language on the CLR”, I get the feeling there won’t be a “Visual F#” sku. Don Syme has more on the news.
  • In other Soma announcement news, Popfly is now in beta. More details on what’s new on the Popfly Team Blog. I haven’t played with Popfly in depth, but I think it’s got huge potential.
  • Scott Guthrie details the upcoming ASP.NET MVC Framework. Personally, I’m not building web apps much these days, so I’m not really invested one way or the other. Given the interest in this approach, it’s nice to see the ASP.NET team respond to the market, though I’m sure someone will complain that we’re trying to kill off the various open-source MVC Web frameworks that have sprung up.
  • Over in Windows Live, they shipped a new version of Live Search Maps, upgraded WL Photo Gallery (which I’ve been digging) to support Flickr and shipped an update to WL Accounts which allows you to link accounts.
  • The Clarius folks keep churning out great tools for software factory developers. The latest is the T4 editor, which brings intellisense, color syntax highlighting and property inspector support for Text Templating Transformation Toolkit (aka T4) files. T4 files are used for code generation in both DSL Toolkit and GAT.
  • David Pallman (again via Sam Gentile) suggests there are only three choices for infrastructure architecture: None/Point-to-point, Centralized/Hub-and-Spoke and Thin/Bus. I get the first two, but his explanation of the third goes to far into the “magic framework” category for my taste. “Physically distributed but logically centralized”? That doesn’t make any sense to me at all.
  • Fellowship of the Ring makes its way onto XBLM. Alas, not in HD so I’ll stick w/ my extended four hour DVD version thankyouverymuch.

Morning Coffee 109

  • I forgot to add a number to my last morning coffee post. However, after extensive research, I have determined that it was #108. So thing are continuing as usual today with #109. On the other hand, do you really want development and architecture opinions from a guy who can barely count? 😄
  • The finalists in the Dream-Build-Play contesthave been announced. I haven’t played any of them yet (some are available for download) but they several of them sure look good.
  • And speaking of gaming, MS announced an Xbox 360 price drop yesterday. So if you want to get in on some of the XNA action, here’s your chance (or you could just build for your PC – take your pick).
  • Finally on the gaming front, if you’re not busy Monday you can watch the first day of Gamefest 2007 online. Get the scoop on XNA 2.0 as well as the new XNA networking support. I, alas, am busy Monday so I’ll have to catch it on demand.
  • On to, you know, actual geek stuff things. Scott Guthrie seems to have retired his LINQ to SQL series and moved on to LINQ to XML. He shows how to build an RSS reader application with LINQ to XML. An oldie demo, but a goodie.
  • Wanna learn F#, there’s a whole site of samples up on CodePlex. (via Don Syme)
  • Jeff Atwood is annoyed at how many different products you have to install to get a current & complete setup of VS 2005. Of course, MS shipped two parts of that stack since VS05 shipped (TFS & DBPro), three service packs (VS05 SP1, SQL 05 SP2 and DBPro SR1) and a major OS upgrade (VS Vista update). Doesn’t the same thing happen with any shipping product after a few years? BTW, if this is such a huge hassle, I wonder why Jeff doesn’t create a slipstreamed VS installer?
  • Udi Dahan has a great post on estimation where he claims “Developers don’t know how to estimate.” No argument, but the way he phrases it sounds like it’s the developer’s fault they suck at estimation. It’s not. Developing – by definition – is building something you’ve never built before. Is it any surprise we suck at estimating how long it will take us to do something we’ve never done before?