Algebraic data types: Difference between revisions
Content added Content deleted
(→{{header|jq}}: def node:) |
(→{{header|jq}}: simplify) |
||
Line 1,105: | 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}` |
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`. |
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''' |
'''bindings.jq''' |
||
Line 1,141: | Line 1,143: | ||
<lang jq>include "bindings" {search: "."}; |
<lang jq>include "bindings" {search: "."}; |
||
⚫ | |||
# Each nonempty node is an array: [Color, Left, Value, Right] |
# Each nonempty node is an array: [Color, Left, Value, Right] |
||
# where Left and Right are nodes. |
# where Left and Right are nodes. |
||
Line 1,146: | Line 1,149: | ||
def B: "⚫"; |
def B: "⚫"; |
||
def R: "🔴"; |
def R: "🔴"; |
||
⚫ | |||
def b(x): bindings({} | x) // empty; |
def b(x): bindings({} | x) // empty; |
||
Line 1,155: | Line 1,156: | ||
def node: [R, [B, .a, .x, .b], .y, [B, .c, .z, .d]]; |
def node: [R, [B, .a, .x, .b], .y, [B, .c, .z, .d]]; |
||
( b([B, [R, [R, {a}, {x}, {x}], {y}, {c}], {z}, {d}]) |
|||
// |
// b([B, [R, {a}, {x}, [R, {b}, {y}, {c}]], {z}, {d}]) |
||
// |
// b([B, {a},{x}, [R, [R, {b}, {y}, {c}], {z}, {d}]]) |
||
// |
// b([B, {a},{x}, [R, {b}, {y}, [R, {c}, {z}, {d}]]]) |
||
| node) // . ; |
|||
// (b([{col}, {a}, {x}, {b}]) |
|||
| [.col, .a, .x, .b ]) ; |
|||
# Input: a node |
# Input: a node |