11(* Decode a JSON tree structure *)
2- type 'a tree =
3- | Node of 'a * 'a tree list
4- | Leaf of 'a
2+ type 'a tree = Node of 'a * 'a tree list | Leaf of 'a
53
64module Decode = struct
75 open Json.Decode
86
97 let rec tree decoder =
10- field " type" string |> andThen (
11- function | "node" -> node decoder
12- | "leaf " -> leaf decoder
13- | _ -> failwith " unknown node type "
14- )
8+ field " type" string
9+ |> andThen ( function
10+ | "node " -> node decoder
11+ | "leaf" -> leaf decoder
12+ | _ -> failwith " unknown node type " )
1513
1614 and node decoder json =
17- Node (
18- (json |> field " value" decoder) ,
19- (json |> field " children " ( array (tree decoder) |> map Array. to_list))
20- )
15+ Node
16+ ( json |> field " value" decoder,
17+ json
18+ |> field " children " ( array (tree decoder) |> map Array. to_list) )
2119
22- and leaf decoder json =
23- Leaf (json |> field " value" decoder)
20+ and leaf decoder json = Leaf (json |> field " value" decoder)
2421end
2522
26- let rec indent =
27- function | n when n < = 0 -> ()
28- | n -> print_string " " ; indent (n - 1 )
23+ let rec indent = function
24+ | n when n < = 0 -> ()
25+ | n ->
26+ print_string " " ;
27+ indent (n - 1 )
2928
3029let print =
31- let rec aux level =
32- function | Node (value , children ) ->
33- indent level;
34- Js. log value;
35- children |> List. iter (fun child -> aux (level + 1 ) child)
36- | Leaf value ->
37- indent level;
38- Js. log value
39- in
40- aux 0
41-
42- let json = {| {
30+ let rec aux level = function
31+ | Node (value , children ) ->
32+ indent level;
33+ Js. log value;
34+ children |> List. iter (fun child -> aux (level + 1 ) child)
35+ | Leaf value ->
36+ indent level;
37+ Js. log value
38+ in
39+ aux 0
40+
41+ let json =
42+ {| {
4343 " type" : " node" ,
4444 " value" : 9 ,
4545 " children" : [{
@@ -59,6 +59,4 @@ let json = {| {
5959} | }
6060
6161let myTree =
62- json |> Json. parseOrRaise
63- |> Decode. tree Json.Decode. int
64- |> print
62+ json |> Json. parseOrRaise |> Decode. tree Json.Decode. int |> print
0 commit comments