F# Type Providers

The FSharp.Data library introduces several TypeProviders. At the time of writing the general purpose TypeProviders include one for XML, JSON and CVS along with TypeProviders specific to Freebase and Worldbank.

Either add a reference to FSharp.Data or use NuGet to install FSharp.Data to work through these examples.

CsvTypeProvider

The CsvTypeProvider (as the name suggests) allows us to interact with Csv data. Here’s some code based upon the Titanic.csv Csv file supplied with FSharp.Data’s source via GitHub.

open FSharp.Data

type TitanicData = CsvProvider<"c:\dev\Titanic.csv", SafeMode=true, PreferOptionals=true>

[<EntryPoint>]
let main argv =     

    let ds = TitanicData.Load(@"c:\dev\Titanic.csv")

    for i in ds.Data do
        printfn "%s" i.Name.Value 

    0 // return an integer exit code

Firstly we open the FSharp.Data namespace, then create a type abbreviation, to the CsvProvider. We pass in the sample data file so that the provider can generate it’s schema.

We can ignore the main function and return value and instead jump straight to the let ds = … where we load the actual data that we want to parse. The type abbreviation used this same file to generate the schema but in reality we could now load any file that matches the expected titanic file schema.

We can now enumerate over the file data using ds.Data and best still is that within Visual Studio we can now use intellisense to look at the headings generated by the CsvProvider, which now appear as properties of the type. i.e. i.Name is an Option type supplied by the schema, hence if we’d had a heading in the Csv named “Passenger Id” we’d now have Passenger showing as a property on the instance I within the loop and hence be able to write like printfn “%i” i.“Passenger Id“.Value.