Reputation: 133
In Julia we can redefine the operator like +,× ,sin, cos and so on. But one interesting thing is that after the redefinition the order among all those amended operators still hold,like multiplication still goes before summation no matter how you redefine your own function,why?
Upvotes: 3
Views: 117
Reputation: 31342
This is simply a function of how operator precedence is defined for infix operators. You can find the precedence table in the manual. Precedence defines how Julia code is parsed into a sequence of nested function calls. You can manually specify precedence with parentheses or traditional function call syntax.
You can see this happening just by asking Julia to parse (but not execute) the code. It returns back a quoted expression, which is printed in a way that mimics the standard way of writing that code in Julia. There are a number of tools that allow you to inspect this quoted expression; one that's helpful to display the nesting of calls is Meta.show_sexpr
.
julia> ex = parse("1 + 2 * 3")
:(1 + 2 * 3)
julia> Meta.show_sexpr(ex)
(:call, :+, 1, (:call, :*, 2, 3))
This is simply stating that it will multiply 2*3 before adding 1 to it. That is entirely based upon the nested structure of the parentheses. Whatever function is bound to *
will get executed first, regardless of its definition. Now compare the results above with things like:
parse("(1 + 2) * 3")
parse("+(1, *(2, 3))")
parse("*(1, +(2, 3))")
Upvotes: 7