Description
openedon Mar 17, 2014
When method extension coupled with multiple dispatch mechanism, we tend to be always find ourselves in the loop of continuing adding disambiguating methods. Seriously, this is unsustainable in the long run.
Consider the following:
# suppose this is defined in base
type A <: BaseT end
+(::A, ::A) = println("A + A") # this needs to be in front
+(::A, ::BaseT) = println("A + BaseT")
+(::BaseT, ::A) = println("BaseT + A")
If someone want to write a package that extends BaseT
, he will need to write
module modB
import Base: BaseT, A, +
type B <: BaseT end
# for the second type, you have to put three methods in front
# in order to reduce ambiguity
+(::A, ::B) = println("A and B")
+(::B, ::A) = println("B and A")
+(::B, ::B) = println("B and B")
+(::B, ::BaseT) = println("B and BaseT")
+(::BaseT, ::B) = println("BaseT and B")
end
If there are n
subtypes of BaseT
in the Base
, O(n^2)
disambiguating methods need to be added.
What's worse, if another one independently creates another package that extends BaseT
, as below:
module modC
import Base: BaseT, A, +
type C <: BaseT end
+(::A, ::C) = println("A and C")
+(::C, ::A) = println("C and A")
+(::C, ::C) = println("C and C")
foo(::C, ::BaseT) = println("C and BaseT")
foo(::BaseT, ::C) = println("BaseT and C")
end
Then when one want to import both packages (even without using
, just import
), there will be ambiguities warnings about +(B, C)
etc.
This issue has caused a lot of headaches for packages that try to define their own customized array types, for example:
- Ambiguities with subtraction operator JuliaStats/DataArrays.jl#51
- New ambiguity warnings JuliaStats/DataArrays.jl#77
Images and some other packages also encounter such problems.
Whereas this might be solved by continuously adding disambiguating methods, problems still exist (or even worse) when you use two or more of these packages together.
Are we going to add disambiguating methods for every pair of array types residing in different packages?
Just try the following, you will see screens full of ambiguities warnings (though just importing either one will be fine):
import DataArrays
import Images
We seriously need a fundamental solution to this.