Overloaded operators: Difference between revisions
Content added Content deleted
(Added C++ implementation) |
(julia example) |
||
Line 222: | Line 222: | ||
"x" | foo #=> [1, "1"]</lang> |
"x" | foo #=> [1, "1"]</lang> |
||
=={{header|Julia}}== |
|||
Most operators in Julia's base syntax are in fact just syntactic sugar for function calls. In particular, the symbols: |
|||
</lang julia> |
|||
* / ÷ % & ⋅ ∘ × ∩ ∧ ⊗ ⊘ ⊙ ⊚ ⊛ ⊠ ⊡ ⊓ ∗ ∙ ∤ ⅋ ≀ ⊼ ⋄ ⋆ ⋇ |
|||
⋉ ⋊ ⋋ ⋌ ⋏ ⋒ ⟑ ⦸ ⦼ ⦾ ⦿ ⧶ ⧷ ⨇ ⨰ ⨱ ⨲ ⨳ ⨴ ⨵ ⨶ ⨷ ⨸ ⨻ |
|||
⨼ ⨽ ⩀ ⩃ ⩄ ⩋ ⩍ ⩎ ⩑ ⩓ ⩕ ⩘ ⩚ ⩜ ⩞ ⩟ ⩠ ⫛ ⊍ ▷ ⨝ ⟕ ⟖ ⟗ |
|||
</lang> |
|||
are parsed in the same precedence as the multiplication operator function *, and the symbols: |
|||
</lang julia> |
|||
+ - ⊕ ⊖ ⊞ ⊟ ∪ ∨ ⊔ ± ∓ ∔ ∸ ≏ ⊎ ⊻ ⊽ ⋎ ⋓ ⧺ ⧻ ⨈ ⨢ ⨣ ⨤ ⨥ ⨦ |
|||
⨧ ⨨ ⨩ ⨪ ⨫ ⨬ ⨭ ⨮ ⨹ ⨺ ⩁ ⩂ ⩅ ⩊ ⩌ ⩏ ⩐ ⩒ ⩔ ⩖ ⩗ ⩛ ⩝ ⩡ ⩢ ⩣ |
|||
</lang> |
|||
are parsed as infix operators with the same precedence as +. There are many other operator |
|||
symbols that can be used as prefix or as infix operators once defined as a function in Julia. |
|||
<br /> |
|||
As a language, much of Julia is organized around the concept of multiple dispatch. Because |
|||
the language dispatches function calls according to the types of the function arguments, |
|||
even the base arthmetic operators are in fact overloaded operators in Julia. |
|||
</br /> |
|||
For example,<lang julia>2 * 3</lang> is sent to the function *(x::Int, y::Int)::Int, whereas <lang julia>2.0 * 3.0</lang> |
|||
is dispatched to the overloaded function *(x::Float64, y::Float64)::Float64. Similarly, string |
|||
concatenation in Julia is with * rather than +, so "hello " * "world" is dispatched to the |
|||
overloaded function *(x::String, y::String)::String, and other types such as matrices also |
|||
have arithmetic operators overloaded in base Julia: |
|||
<lang julia>julia> x = [1 2; 3 4]; y = [50 60; 70 80]; x + y |
|||
2×2 Matrix{Int64}: |
|||
51 62 |
|||
73 84 |
|||
</lang> |
|||
Users may define their own overloaded functions in similar ways, whether or not such operators |
|||
are already used in base Julia. In general, it is considered bad practice, as "operator piracy", to define a user overloaded |
|||
operator which dispatches on the same types for which base Julia has already defined the same |
|||
function. Instead, user defined types can be best made to have analogous operators defined for |
|||
the new type so as to leverage existing code made for analagous base types. This can allow generic |
|||
functions to use new types in efficient and constructive ways. |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |