简体   繁体   English

F#JSON连接的任务

[英]F# JSON connected task

Suppose I have the following code for my custom union: 假设我的自定义联合具有以下代码:

type JSON =
| Object of (string * JSON) list
| Array of JSON list
| Number of double
| Boolean of bool
| Null
| String of string

How can I implement the function 'find the sum of all numbers in JSON object'? 如何实现“在JSON对象中查找所有数字的总和”功能? let summarizer (tree : JSON) : int

It should recursively traverse the JSON tree and return as a result the sum of all numbers in JSON object. 它应该递归地遍历JSON树,并因此返回JSON对象中所有数字的总和。

You should start by considering each individual case of the JSON type, and deciding how that case would contribute to the sum. 您应该首先考虑JSON类型的每种情况,并确定该情况如何影响总和。 I'll go from bottom to top since the top cases are the harder ones: 我将自下而上,因为最困难的情况是:

  • String - would add 0.0 to the sum. String -将总和加0.0。
  • Null - would add 0.0 to the sum. Null -将总和加0.0。
  • Boolean - would add 0.0 to the sum. Boolean -将总和加0.0。
  • Number - would add itself to the sum. Number -将自身加到总和上。
  • Array - Go through the individual JSON items in the array, and calculate each of their individual sums. Array -遍历Array的各个JSON项,然后计算它们各自的总和。 All those sums added together get added to the running total sum. 所有这些总和加到运行总和中。
  • Object - Go through the pairs, and in each pair, the second item is a JSON object that would have a sum. Object -遍历各对,然后在每对中,第二项是一个具有总和的JSON对象。 Sum all those up, and you get a number to add to the sum. 将所有这些加起来,就得到一个数字加到总和上。

And now we have the function almost written for us already! 现在,我们已经几乎为我们编写了该函数!

let rec sumOfJson = function
    | Object list -> List.sumBy (snd >> sumOfJson) list
    | Array list -> List.sumBy sumOfJson list
    | Number n -> n
    | Boolean _
    | Null
    | String _ -> 0.0

If you don't understand the snd >> sumOfJson part, that's exactly equivalent to fun x -> x |> snd |> sumOfJson . 如果您不理解snd >> sumOfJson部分,那完全等效于fun x -> x |> snd |> sumOfJson Here, x is a string * JSON pair, so that's equivalent to fun (_, json) -> sumOfJson json . 在这里, x是一个string * JSON对,所以等效于fun (_, json) -> sumOfJson json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM