HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Functional Programming style in F#

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
functionalprogrammingstyle

Problem

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 (obj:'T) =
    use ms = new MemoryStream()
    (new DataContractJsonSerializer(typeof)).WriteObject(ms, obj)
    Encoding.Default.GetString(ms.ToArray())

let GetObjectFromJson (json:string) : 'T =
    use ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(json))
    let obj = (new DataContractJsonSerializer(typeof)).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  HttpWebResponse
    use stream = res.GetResponseStream()
    use sr = new StreamReader(stream)
    let data = sr.ReadToEnd()
    data


// Model.fs
module Model

open System.Runtime.Serialization

[]
type exchangeRate = {
    []
    toCurrency:string;
    []
    rate:decimal;
    []
    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")

Solution

It looks good! Just a couple of points.

-
Instead of

let data = sr.ReadToEnd()
data


you can write

sr.ReadToEnd()


-
sprintf is more idiomatic than String.Format.

-
displayExchangeRate would be better written as a loop or using
List.iter (or Seq.iter).

-
DataContractJsonSerializer.WriteObject uses Encoding.UTF8, but you're decoding with Encoding.Default, which returns the OS's current ANSI code page.

Code Snippets

let data = sr.ReadToEnd()
data
sr.ReadToEnd()

Context

StackExchange Code Review Q#59030, answer score: 4

Revisions (0)

No revisions yet.