Dear Julia users,

if you have an AbstractSupertype and a concrete Subtype, then the dispatch 
evidently works great to make sure that if you define 
f(x::AbstractSupertype) and f(x::Subtype), the latter will be called if f 
is called with an argument of type Subtype.

I am writing some code in which I have two functions f and g which should 
have the following behaviour:
function f(x::AbstractType)
# if g is implemented for concrete subtype of x, then define f using g(x)
# otherwise, throw MethodError
end
function g(x::AbstractType)
# if g is implemented for concrete subtype of x, then define g using f(x)
# otherwise, throw MethodError
end

So the idea would be that the subtype only has to implement f or g, and 
these functions would make sure that both work. Think of e.g. a mutating 
and non mutating version of a function, where the subtype only needs to 
implement of them. If the subtype implements neither, one should get a 
MethodError. My initial guess was:
f(x::AbstractType) = method_exists(g,(typeof(x),)) ? (do something using g(x
)) : throw(MethodError())
g(x::AbstractType) = method_exists(f,(typeof(x),)) ? (do something using f(x
)) : throw(MethodError())

While this works as long as the Subtype defines at least one of the both 
functions, it runs in circles if there is no specific implementation of 
either function, since method_exists still thinks that there is a matching 
function, namely the one for AbstractType. So the MethodError never gets 
thrown.

So what would be the best way to tackle this problem? I was thinking of 
using methodswith(typeof(x)) to get all specific implementations for 
Subtype, and then trying to find wether this contains f or g. Methodswith 
returns an Array{Method,1}. However, I do not know how to create the 
corresponding Method object that I want to look for. What is the best way 
to find something in the output of methodswith? Is this by converting this 
output to a string? Better strategies for solving the problem above are 
certainly welcome, cause this doesn't look very elegant.

Reply via email to