Algebraic data types: Difference between revisions
→{{header|jq}}: simplify
(→{{header|jq}}: def node:) |
(→{{header|jq}}: simplify) |
||
Line 1,105:
jq does not have built-in support for pattern matching in the sense of the present task description, but the following `bindings` function takes advantage of the way in which singleton-key JSON objects can be used as variables for pattern-matching. In effect, jq expressions such as `{a}`
can be used as variables in the pattern definitions, and after matching, the corresponding values can be referenced by jq expressions such as `.a`.
Notice also how various features of jq come together to simplify the implementation of the `balance` function.
'''bindings.jq'''
Line 1,141 ⟶ 1,143:
<lang jq>include "bindings" {search: "."};
def E: []; # the empty node▼
# Each nonempty node is an array: [Color, Left, Value, Right]
# where Left and Right are nodes.
Line 1,146 ⟶ 1,149:
def B: "⚫";
def R: "🔴";
▲def E: []; # the empty node
def b(x): bindings({} | x) // empty;
Line 1,155 ⟶ 1,156:
def node: [R, [B, .a, .x, .b], .y, [B, .c, .z, .d]];
(
//
//
//
| node) // . ;
# Input: a node
|