Amade
Amade

Reputation: 3998

What does assignment like x\y = 1 mean in Julia?

While experimenting with Julia 1.0, I've noticed that I can do something like this:

x\y = 1

The REPL then shows:

\ (generic function with 1 method)

which means its a valid assignment (the interpreter doesn't complain). However, x, y, and x\y all remain undefined.

What is the meaning of such expression?

Upvotes: 1

Views: 112

Answers (1)

hckr
hckr

Reputation: 5583

It is a new function definition that (kind of) shadows the left division operator \ in Base, since the left division operator is already defined for some types in Julia. The new function definition is \(x,y) = 1 (the names of function parameters do not matter) which works for all types of variables. This will prevent julia from loading Base.\ due to name conflict. No matter what the input is your new \ will return the same value.

julia> x\y = 5

julia> a = 3; b = 4;
julia> a\b
5
julia> c = "Lorem ipsum"; d = "dolor";
julia> c\d
5

If you have already used the \ that is defined in Base, your redefinition will throw an error saying that extending Base.\ requires an explicit import with import Base.\. The behavior of defining \ after import Base.\ however will be different. It will extend the operator Base.\.

julia> 1\[1,3]
2-element Array{Float64,1}:
 1.0
 3.0

julia> import Base.\

julia> x\y=3
\ (generic function with 152 methods)

julia> 1\[1,3]
2-element Array{Int64,1}:
 3
 3

Upvotes: 8

Related Questions