gpt4 book ai didi

F# 遍历序列并为序列的每个元素调用一个函数

转载 作者:行者123 更新时间:2023-12-04 18:05:43 25 4
gpt4 key购买 nike

我需要为序列的每个元素调用一个函数,目前我已经尝试过
Seq.iter 和 Seq.map 但它们分别返回 unit 和 'a ->'c 而不是我需要的 Json。

我试过了

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

最佳答案

您需要 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(并解析它)。

关于F# 遍历序列并为序列的每个元素调用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28693535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com