Define a primitive data type: Difference between revisions

Content added Content deleted
m (→‎{{header|jq}}: spacing)
Line 747: Line 747:
In the following, we define a new type named "smallint", with arithmetic operations that either return the "smallint" one would expect from ordinary arithmetic, or else return nothing (an empty stream), as opposed to returning null or raising an error. The choice of an empty stream is made to highlight this alternative.
In the following, we define a new type named "smallint", with arithmetic operations that either return the "smallint" one would expect from ordinary arithmetic, or else return nothing (an empty stream), as opposed to returning null or raising an error. The choice of an empty stream is made to highlight this alternative.
By design, jq's types are constrained to be JSON types, so 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:
By design, jq's types are constrained to be JSON types, so
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:
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)"
<lang jq>def pp:
if type == "object" and has("type") then "\(.type)::\(.value)"
else .
else .
end;</lang>Our instances of smallint will look like this: {"type": "smallint", "value": 0}
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 inequality (== and !=) can be used for the instances of smallint.
inequality (== and !=) can be used for the instances of smallint.


In fact the builtin comparison functions (< and >) will also have the correct semantics, as will
In fact the builtin comparison functions (< and >) will also have the correct semantics, as will sort and unique.
sort and unique.


As of this writing, the official release of jq does not support modules, so we will not use jq's new module system here, but it would allow us to place all the smallint functions in a Smallint module.
As of this writing, the official release of jq does not support modules, so we will not use jq's new module system here, but it would allow us to place all the smallint functions in a Smallint module.