Reputation: 14561
I saw in someone code that they were using the +
operator as if it was a function by doing +(1,2,3)
. Is it possible to use operators as functions in Julia?
In addition, I also saw things like A ⊗ B
, where the behaviour of ⊗
was customizable. How can I do such a thing, and is there a list of symbols I can use in this way?
Upvotes: 2
Views: 498
Reputation: 14561
Yes, you indeed can use operators as functions in Julia.
In Julia, most operators are just functions with support for special syntax. (The exceptions are operators with special evaluation semantics like && and ||. These operators cannot be functions since Short-Circuit Evaluation requires that their operands are not evaluated before evaluation of the operator.) Accordingly, you can also apply them using parenthesized argument lists, just as you would any other function:
julia> 1 + 3 + 5
9
julia> +(1,3,5)
9
julia> 1 * 3 * 5
15
julia> *(1,3,5)
15
julia> h = *;
julia> h(1,3,5)
15
In addition, Julia allows you to define your own meaning to operators, and makes quite a few symbols available for the purpose. You can find the list of available symbols here:| https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm
and define them as such:
⊗(a, b) = a * 3 - b # or some other arbitrary thing
a ⊗ b == a * 3 - b # true
Upvotes: 8