This post contributed by Paul Blair, team lead at Cyrus Innovation.
Developers spend a lot of time writing code to access data and make it available in a form their programs can manipulate. Recently, I attended a presentation by Keith Battocchi, a contractor at Microsoft Research, at the advanced track of the recent F# Progressive Tutorials in New York City. The topic was "type providers," a new feature of F# that can make data access a lot easier.
Here is an example from Keith's presentation: I'll start with an F# script that loads two libraries and executes one line of code which defines a type (if the word "type" bothers you, think "class"):
I'm using Stack Overflow as an example, but I could have put in any other arbitrary OData endpoint--e.g., WordPress Answers, or the eBay catalog. (OData is an open web protocol for querying data.)
I now have fully-typed access to Stack Overflow posts that are exposed as an OData service. This means, for example, that I get autocompletion in my IDE:
In other words, the ODataServices type provider goes off to the web, reads Stack Overflow's OData schema, and generates a set of classes for me specific to the structure of the Stack Overflow data:
And finally, here's the finished query to get the number of posts on Stack Overflow tagged with "f#" -- evaluated in the F# interactive shell:
(For .NET devotees, notice how F# now supports LINQ query expressions, and allows aggregate functions directly in the query rather than requiring method call syntax as in C#.)
If you visit http://www.odata.org/ecosystem#liveservices you can see just how much data it's possible to access via OData--which type providers allow you to grab and manipulate by just entering a URL and doing simple queries in F# Interactive. F# 3.0 ships with two more type providers, one for SQL database access--this basically generates classes using the database structure the way ActiveRecord does--and one for WSDL web service endpoints.
You can write your own type providers as well. For instance, if you have FIX messages coming over the wire, you can create a type provider to generate a corresponding class for each message type. When the FIX protocol gets updated to a new version, you just have to read in the new schema file and recompile, and you have a new set of classes corresponding to the new schema. You now have a compile-time check that your old code can work with the new schema: If your code accesses data structures that aren't there any more in the new version, your code will fail to build.
I think that's pretty awesome.