I'm normally a C# developer, but I've started to learn F# and I want to make sure I'm writing code in a functional way that suits the language. I've quickly pieced this together with my knowledge from reading Functional Programming for the Real World and various material from the Web.
Please look and provide feedback on style, layout or anything you want (Program.fs is where the meat is):
// DataUtils.fs
module DataUtils
open System.IO
open System.Runtime.Serialization.Json
open System.Text
let GetJsonFromObject<'T> (obj:'T) =
use ms = new MemoryStream()
(new DataContractJsonSerializer(typeof<'T>)).WriteObject(ms, obj)
Encoding.Default.GetString(ms.ToArray())
let GetObjectFromJson<'T> (json:string) : 'T =
use ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(json))
let obj = (new DataContractJsonSerializer(typeof<'T>)).ReadObject(ms)
obj :?> 'T
// Web.fs
module Web
open System
open System.Net
open System.IO
let GetJsonFromWebRequest url =
let req = WebRequest.Create(new Uri(url)) :?> HttpWebRequest
req.ContentType <- "application/json"
let res = req.GetResponse () :?> HttpWebResponse
use stream = res.GetResponseStream()
use sr = new StreamReader(stream)
let data = sr.ReadToEnd()
data
// Model.fs
module Model
open System.Runtime.Serialization
[<DataContract>]
type exchangeRate = {
[<field: DataMember(Name = "to")>]
toCurrency:string;
[<field: DataMember(Name = "rate")>]
rate:decimal;
[<field: DataMember(Name = "from")>]
fromCurrency:string }
// Program.fs
module Program
open System
open Model
let getExchangeRate fromCurrency toCurrency =
let url = String.Format("http://rate-exchange.appspot.com/currency?from={0}&to={1}", fromCurrency, toCurrency)
let json = Web.GetJsonFromWebRequest url
let rate:exchangeRate = DataUtils.GetObjectFromJson json
rate
let rec displayExchangeRate currencies =
match currencies with
| [] -> []
| (a, b)::tl ->
let r = getExchangeRate a b
printfn "%s -> %s = %A" a b r.rate
displayExchangeRate tl
let currencies = [
("GBP", "EUR")
("GBP", "USD")
("EUR", "GBP")
("EUR", "USD")
("USD", "GBP")
("USD", "EUR") ]
displayExchangeRate currencies |> ignore
printfn "Press any key to exit"
let input = Console.ReadKey()
As you can see it's not doing an awful lot at the moment, just getting some exchange rates from a REST service and displaying them. The next step would be to add exchange rates to the database. I'd normally use Entity Framework for this, but given that Functional Programming is partly about reducing the amount of state that is held, is EF even the way to go?