3

I don't know how to locally extend a Base operator and I couldn't find anything about that.
I can obviously redefine it in the global scope (REPL or module) doing :

import Base.-

-(x, y::Nothing) = nothing
-(x::Nothing, y) = nothing

But I would like to have this to stay private in my module and not exported automatically to the global scope, in order not to pollute it, and still be able to use extensions in some functions in the module.
I tried let ... end blocks or even to redefine it inside my module's functions but it seems to prevent from importing Base properly.
I would like something like :

module MyModule
export my_visible_function

function -(x, y::SomeType) 
# Base.- extension with x and ::SomeType
end

function my_visible_function()
# code using Base.- extension
end

end

Is there anyway to do that?

Thanks for help.

jejouch
  • 31
  • 3

1 Answers1

2

You can create your own - function that shadows Base.:- within your module. This will work as long as Base.:- is not explicitly called before you define your - function in your module. (More on that below.) Then you can define your - function in such a way that it falls back to Base.:- for most calls.

Here's an example:

module A
export foo

-(::Any, ::Nothing) = nothing
-(x, y) = Base.:-(x, y)
foo(x, y) = x - y

end
julia> using .A

julia> foo(1, 3)
-2

julia> foo(1, nothing)

julia> 1 - 3
-2

julia> 1 - nothing
ERROR: MethodError: no method matching -(::Int64, ::Nothing)

Here's an example that shows that it's ok to use Base.:- in a function definition before you define your own - function:

# This works.

module B
export foo, bar

bar(x, y) = Base.:-(x, y)

-(::Any, ::Nothing) = nothing
-(x, y) = Base.:-(x, y)

foo(x, y) = x - y

end

The only time this won't work is if you explicitly call - (from Base) before you define your own -. Here's an example of that:

julia> module C
       export foo
       
       1 - 3
       -(::Any, ::Nothing) = nothing
       -(x, y) = Base.:-(x, y)
       foo(x, y) = x - y
       
       end
ERROR: error in method definition: function Base.- must be explicitly imported to be extended
Cameron Bieganek
  • 7,208
  • 1
  • 23
  • 40