Neat Sample: F# and Freebase
Jomo Fisher – The web service at Freebase.com lets you access all sorts of structured data from a web service. Here’s a sample that shows you how to access this data from F#. It uses DataContract and the JSON serializer. The code below reads and prints the elements of the periodic table.
Code Snippet
// Freebase.fsx
// Example of reading from freebase.com in F# using DataContract and JSON serializer
// by Jomo Fisher
#r "System.Runtime.Serialization"
#r "System.ServiceModel.Web"
#r "System.Web"
#r "System.Xml"
open System
open System.IO
open System.Net
open System.Text
open System.Web
open System.Security.Authentication
open System.Runtime.Serialization
[<DataContract>]
type Result<'TResult> = {
[<field: DataMember(Name="code") >]
Code:string
[<field: DataMember(Name="result") >]
Result:'TResult
[<field: DataMember(Name="message") >]
Message:string
}
[<DataContract>]
type ChemicalElement = {
[<field: DataMember(Name="name") >]
Name:string
[<field: DataMember(Name="boiling_point") >]
BoilingPoint:string
[<field: DataMember(Name="atomic_mass") >]
AtomicMass:string
}
let Query<'T>(query:string) : 'T =
let query = query.Replace("'","\"")
let queryUrl = sprintf "https://api.freebase.com/api/service/mqlread?query=%s" "{\"query\":"+query+"}"
let request : HttpWebRequest = downcast WebRequest.Create(queryUrl)
request.Method <- "GET"
request.ContentType <- "application/x-www-form-urlencoded"
let response = request.GetResponse()
let result =
try
use reader = new StreamReader(response.GetResponseStream())
reader.ReadToEnd();
finally
response.Close()
let data = Encoding.Unicode.GetBytes(result);
let stream = new MemoryStream()
stream.Write(data, 0, data.Length);
stream.Position <- 0L
let ser = Json.DataContractJsonSerializer(typeof<Result<'T>>)
let result = ser.ReadObject(stream) :?> Result<'T>
if result.Code<>"/api/status/ok" then
raise (InvalidOperationException(result.Message))
else
result.Result
let elements = Query<ChemicalElement array>("[{'type':'/chemistry/chemical_element','name':null,'boiling_point':null,'atomic_mass':null}]")
elements |> Array.iter(fun element->printfn "%A" element)
Let me know if there are other F# samples you’d like to see.
This posting is provided "AS IS" with no warranties, and confers no rights.