Define a primitive data type: Difference between revisions

jq
(Adds Clojure sample usage output)
(jq)
Line 743:
var z = new Num(11); //TypeError
</lang>
 
=={{header|jq}}==
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:
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}
 
This definition ensures that jq's basic tests for equality and
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
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.
 
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
| if (i|type) == "number" and i == (i|floor) and i > 0 and i < 11 then {"type": "smallint", "value": i}
else empty
end ;
 
# A convenience function to save typing:
def s(i): smallint(i);
 
# To convert from the pretty-print representation back to smallint:
def tosmallint:
if type == "string" and startswith("smallint::") then
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 minus(a;b): smallint(a.value - b.value);
def times(a;b): smallint(a.value * b.value);
def mod(a;b): smallint(a.value % b.value);
def divide(a;b): smallint( (a.value / b.value) | floor );</lang>Examples:<lang jq>s(1) < s(3) # => true
add( s(1); s(2)) | pp # "smallint::3"
add( s(6); s(6)) # (nothing)</lang>
 
=={{header|Lasso}}==
2,503

edits