In the bs-json library there is an example provided for converting a json structure to a tree using the andThen
combinator. The original example can be found here on github in the ML interface file. Copying the function decodeTree
from this file to the browser reason tools shows a syntax error.
Would very much appreciate any pointers for getting this to work.
My attempt at translating it to Reason3 results in a type error. This is the code:
type tree('a) =
| Node('a, list(tree('a)))
| Leaf('a);
let json = {| {
"type": "node",
"value": 9
"children": [{
"type": "leaf",
"value": 5,
"children": [{
"type": "leaf",
"value": 3
}, {
"type": "leaf",
"value": 2
}]
}, {
"type": "leaf",
"value": 4
}]
} |};
let decodeTree = (decodeValue, json) =>
Json.Decode.(
field("type", string)
|> andThen(type_ =>
switch type_ {
| "node" =>
Node(
field("value", decodeValue),
field("children", children =>
children |> array(decodeTree) |> map(Array.to_list)
)
)
| "leaf" => Leaf(field("value", decodeValue))
}
)
);
let myTree = json |> Json.parseOrRaise |> decodeTree(Json.Decode.int);
This is the type error,
This has type:
tree('a)
But somewhere wanted:
Json.Decode.decoder('b) (defined as (Js.Json.t) => 'b)