Define a primitive data type: Difference between revisions

Content added Content deleted
(jq)
m (→‎{{header|jq}}: spacing)
Line 750: Line 750:
jq's type system cannot be used to create a new type, but we can create a
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
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
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:
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}
<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}


This definition ensures that jq's basic tests for equality and
This definition ensures that jq's basic tests for equality and
Line 764: Line 765:


To generate instances of smallint, we define a function,
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
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}
| if (i|type) == "number" and i == (i|floor) and i > 0 and i < 11 then {"type": "smallint", "value": i}
else empty
else empty
Line 778: Line 778:
split("::") | smallint( .[1] | tonumber )
split("::") | smallint( .[1] | tonumber )
else empty
else empty
end ;</lang>That leaves just basic arithmetic operations: add minus times mod div <lang jq>
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 minus(a;b): smallint(a.value - b.value);
def times(a;b): smallint(a.value * b.value);
def times(a;b): smallint(a.value * b.value);