Skip to content

Instantly share code, notes, and snippets.

@semuserable
Last active August 5, 2016 07:51
Show Gist options
  • Save semuserable/f27533c952414a49d3e89514235fe976 to your computer and use it in GitHub Desktop.
Save semuserable/f27533c952414a49d3e89514235fe976 to your computer and use it in GitHub Desktop.
open FSharp.Data
open FSharp.Data.JsonExtensions
open System.IO
open System
module City =
type T = City of string
let Kyiv = City "Киев"
let Kharkiv = City "Харьков"
let value (City c) = c
module Currency =
type T = Currency of string
let USD = Currency "USD"
let EUR = Currency "EUR"
let value (Currency c) = c
type JsonPath = Home | FinanceUa
let parsedJson jsonPath =
match jsonPath with
| Home ->
(__SOURCE_DIRECTORY__, "finance_ua.json" )
|> Path.Combine
|> File.ReadAllText
|> JsonValue.Parse
| FinanceUa ->
"http://resources.finance.ua/ru/public/currency-cash.json"
|> JsonValue.AsyncLoad
|> Async.RunSynchronously
let getCityId jsonValue name =
let byValue (t:string * JsonValue) = (snd t).AsString() = name
let cityIds = jsonValue?cities.Properties
|> Array.filter byValue
|> Array.map (fun t -> fst t)
match cityIds.Length with
| 0 -> None
| _ -> Some <| Array.head cityIds
let getOrganizationsById jsonValue id =
let byCityId v = v?cityId.AsString() = id;
let allOrganizations = jsonValue?organizations.AsArray()
allOrganizations |> Array.filter byCityId
let getAverageByOrganizations currency organizations =
let byAskKey t = (snd t)?ask.AsFloat()
let byCurrency t = fst t = currency
let forCurrencies v = v?currencies.Properties |> Array.filter byCurrency
organizations
|> Array.collect forCurrencies
|> Array.map byAskKey
|> Array.average
let getAverageByCity jsonValue city currency =
let name = City.value <| city
let cityId = getCityId jsonValue name
match cityId with
| Some id ->
getOrganizationsById jsonValue id
|> getAverageByOrganizations (Currency.value currency)
|> Some
| None -> None
[<EntryPoint>]
let main argv =
let json = parsedJson FinanceUa
let kyivAverage = getAverageByCity json City.Kyiv Currency.USD
printfn "%A" kyivAverage
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment