Define a primitive data type: Difference between revisions

m
(jq)
m (→‎{{header|jq}}: spacing)
Line 750:
jq's type system cannot be used to create a new type, but we can create a
parallel type system based on JSON objects. We shall do so using
the convention that if an object has a key named "type", then the type of the object will be the given value:<lang jq>def typeof:
type of the object will be the given value:<lang jq>def typeof:
if type == "object" and has("type") then .type else type end;</lang>We also define a generic "pretty-print" filter:
<lang jq>def pp: if type == "object" and has("type") then "\(.type)::\(.value)" else . end;</lang>Our instances of smallint will look like this: {"type": "smallint", "value": 0}
else .
end;</lang>Our instances of smallint will look like this: {"type": "smallint", "value": 0}
 
This definition ensures that jq's basic tests for equality and
Line 764 ⟶ 765:
 
To generate instances of smallint, we define a function,
smallint(i), that will return an instance corresponding to an integer, i, if it is in range. As noted above, it will otherwise return nothing at all (as opposed to null or raising an error):<lang jq>def smallint(i): i as $i
null or raising an error):<lang jq>def smallint(i): i as $i
| if (i|type) == "number" and i == (i|floor) and i > 0 and i < 11 then {"type": "smallint", "value": i}
else empty
Line 778:
split("::") | smallint( .[1] | tonumber )
else empty
end ;</lang>That leaves just basic arithmetic operations: add minus times mod div <lang jq>def add(a;b): smallint(a.value + b.value);
def add(a;b): smallint(a.value + b.value);
def minus(a;b): smallint(a.value - b.value);
def times(a;b): smallint(a.value * b.value);
2,502

edits