2015-02-24 49 views
4

我需要爲一個序列的每個元素調用一個函數,目前我已經嘗試過 Seq.iter和Seq.map,但它們返回的是單元和'a - > 'c分別,而不是我需要的Json。F#遍歷序列併爲每個序列元素調用一個函數

我已經試過

Seq.iter (fun _ (a,b,c,d) -> iterateThroughMySequnce a b c d()) sequence 
Seq.fold (fun _ (a,b,c,d) -> iterateThroughMySequnce a b c d()) sequence 

,但我沒有得到的JSON預期收益類型。需要以下其中評論說,代碼「事情是這樣的」

誰能幫助感謝

open Newtonsoft.Json.Linq 

type Json = 
    | JObj of Json seq 
    | JProp of string * Json 
    | JArr of Json seq 
    | JVal of obj 

let (!!) (o: obj) = JVal o 

let rec toJson = function 
    | JVal v -> new JValue(v) :> JToken 
    | JProp(name, (JProp(_) as v)) -> new JProperty(name, new JObject(toJson v)) :> JToken 
    | JProp(name, v) -> new JProperty(name, toJson v) :> JToken 
    | JArr items -> new JArray(items |> Seq.map toJson) :> JToken 
    | JObj props -> new JObject(props |> Seq.map toJson) :> JToken 

let sequence = seq { yield "USD", 12.36M, 156.32M, 18.23M 
        yield "JPY", 13.36M, 564.32M, 17.23M 
        yield "GBP", 14.36M, 516.32M, 120.23M } 

let iterateThroughMySequnce a b c d() = 
    JObj [JProp("CurrencyCode", !! a); 
      JProp("TotalPerCurrencyBeforeExchange", !! b); 
      JProp("ExchangeRate", !! c); 
      JProp("TotalPerCurrencyAfterExchange", !! d)]; 

let k = 
    JObj [ 
     JProp("InvoiceNumber", !! "13456789"); 
     JProp("InvoiceDate", !! "21/12/2015"); 
     JProp("InvoiceCurrency", !! "USD"); 
     JProp("InvoiceProfitMargin", !! 2.3); 
     JProp("InvoicePaymentCurrencyToEuroExchangeRate", !! 0.8658745M); 
     JProp("InvoicePeroid", !! "01/01/2015 00:00:00 - 01/02/2015 23:59:59"); 
     JProp(
      "Transaction", 
       JArr [ 
        //Something like this 
        Seq.iter (fun (a,b,c,d) -> iterateThroughMySequnce a b c d()) sequence 
       ]) 
     JProp("TransactionForPeroid", !! 254584.00M); 
     JProp("InvoicingAmountWithProfitMarginApplied", !! 8452.01M); 
     JProp("InvoicingAmountWithProfitMarginAppliedInEuro", !! 7851.28); 
    ] 

let json = toJson k 

回答

6

你需要Seq.map,這將輸入序列爲輸出序列(和原來每個元素成新值使用指定的功能)。你的代碼幾乎是正確的,但呼叫不應被包裹在另一個列表:

JProp(
    "Transaction", 
     JArr (Seq.map (fun (a,b,c,d) -> iterateThroughMySequnce a b c d()) sequence) 
) 

,如果你改變你的iterateThroughMySequence函數接受一個元組(並且也應該有不同的名稱,您可以讓這個更好的,因爲它不是迭代)

let formatItemAsJson (a,b,c,d) = 
    JObj [JProp("CurrencyCode", !! a); 
     JProp("TotalPerCurrencyBeforeExchange", !! b); 
     JProp("ExchangeRate", !! c); 
     JProp("TotalPerCurrencyAfterExchange", !! d)]; 

// Later in the main part of code 
JProp("Transaction", JArr (Seq.map iterateThroughMySequnce sequence)) 

除此之外,F#的數據庫自帶JsonValue類型(見the API reference),它實現了一些你在這裏做什麼 - 它可以讓你構建&格式JSON(也分析它)。

相關問題