Overloaded operators: Difference between revisions

Line 72:
16
</pre>
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
Many of jq's built-in operators are "overloaded" in the sense that they
can be used on more than one built-in jq data type, these being: "null", "boolean", "string", "object"
and "array".
 
The prime example of an overloaded operator in jq is `+`, which is defined on:
<pre>
null x ANY # additive zero
ANY x null # additive zero
number x number # addition
array x array # concatenation
object x object # coalesence
</pre>
 
Note that `+` is symmetric except for its restriction to object x object, as illustrated by:
<lang jq>{"a":1} + {"a": 2} #=> {"a": 2}
 
{"a":2} + {"a": 1} #=> {"a": 1}</lang>
Most of the other operators that are usually thought of as "arithmetic" are also overloaded, notably:
<pre>
-: array x array # e.g. [1,2,1] - [1] #=> [2]
*: string x number # e.g. "a" * 3 #=> "aaa"
/: string x string # e.g. "a/b/c" / "/"' #=> ["a","b","c"]
</pre>
 
The comparison operators (<, <=, ==, >=, >) are defined for all JSON entities and thus
can be thought of as being overloaded, but this is only because jq defines a total order on JSON entities.
 
The comparison operators can also be used on non-JSON entities as well, e.g.
<lang jq>
0 < infinite #=> true
nan < 0 #=> true
</lang>
 
The logical operators (`and`, `or`, `not`) are also defined for all JSON entities, their logic being
based on the idea that the only "falsey" values are `false` and `null`.
 
Whether a function (meaning a given name/arity pair) is "overloaded" or not depends entirely on its definition,
it being understood that jq functions with the same name but different arities can have entirely unrelated definitions.
 
`length/0` is defined on all JSON entities except `true` and `false`. Note that it is defined
as the absolute value on JSON numbers, and that:
<lang jq>nan|length #=> null</lang>
 
It is also worth pointing out that a single name/arity function can have multiple definitions within
a single program, but normal scoping rules apply so that in any one context, only one definition is
directly accessible. The functionality of the "outer" definition, however, can be accessed indirectly,
as illustrated by the following contrived example:
<lang jq>def foo:
def outer_length: length;
def length: outer_length | tostring;
[outer_length, length];
 
"x" | foo #=> [1, "1"]</lang>
 
=={{header|Nim}}==
Nim allows overloading of operators. There is no restrictions regarding types of arguments when overloading an operator. For instance, we may define a vector type and addition of vectors:
2,442

edits