Freigeben über


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

  1. // Freebase.fsx

  2. // Example of reading from freebase.com in F# using DataContract and JSON serializer

  3. // by Jomo Fisher

  4. #r "System.Runtime.Serialization"

  5. #r "System.ServiceModel.Web"

  6. #r "System.Web"

  7. #r "System.Xml"

  8. open System

  9. open System.IO

  10. open System.Net

  11. open System.Text

  12. open System.Web

  13. open System.Security.Authentication

  14. open System.Runtime.Serialization

  15. [<DataContract>]

  16. type Result<'TResult> = {

  17.     [<field: DataMember(Name="code") >]

  18.     Code:string

  19.     [<field: DataMember(Name="result") >]

  20.     Result:'TResult

  21.     [<field: DataMember(Name="message") >]

  22.     Message:string

  23.     }

  24. [<DataContract>]

  25. type ChemicalElement = {

  26.     [<field: DataMember(Name="name") >]

  27.     Name:string

  28.     [<field: DataMember(Name="boiling_point") >]

  29.     BoilingPoint:string

  30.     [<field: DataMember(Name="atomic_mass") >]

  31.     AtomicMass:string

  32.     }

  33. let Query<'T>(query:string) : 'T =

  34.     let query = query.Replace("'","\"")

  35.     let queryUrl = sprintf "https://api.freebase.com/api/service/mqlread?query=%s" "{\"query\":"+query+"}"

  36.     let request : HttpWebRequest = downcast WebRequest.Create(queryUrl)

  37.     request.Method <- "GET"

  38.     request.ContentType <- "application/x-www-form-urlencoded"

  39.     let response = request.GetResponse()

  40.     let result =

  41.         try

  42.             use reader = new StreamReader(response.GetResponseStream())

  43.             reader.ReadToEnd();

  44.         finally

  45.             response.Close()

  46.     let data = Encoding.Unicode.GetBytes(result);

  47.     let stream = new MemoryStream()

  48.     stream.Write(data, 0, data.Length);

  49.     stream.Position <- 0L

  50.     

  51.     let ser = Json.DataContractJsonSerializer(typeof<Result<'T>>)

  52.     let result = ser.ReadObject(stream) :?> Result<'T>

  53.     if result.Code<>"/api/status/ok" then

  54.         raise (InvalidOperationException(result.Message))

  55.     else

  56.         result.Result

  57. let elements = Query<ChemicalElement array>("[{'type':'/chemistry/chemical_element','name':null,'boiling_point':null,'atomic_mass':null}]")

  58. 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.