Hi,
The interface to my package includes two functions, f
, and g
that can be implemented by users for their types. In the package, f
and g
are empty generic functions, so MethodError
s will be thrown if they are not implemented for the user’s type. f
is part of the core interface, and, if f
is implemented, there is an easy way to construct g
:
function g(x)
y = f(x)
return modify(y)
end
However, some functionality of the package only requires g
, and f
is essentially impossible to implement for some user types while g
(skipping the intermediate y
) is easy, so I want the user to only have to implement g
if they only want to use that part of the package. So my question is is there a way to provide a default implementation of g
using f
only when f
is available?
If you want details, the actual use case is POMDPs.jl
and GenerativeModels.jl
where f
is transition
and g
is generate_s
.
What I have tried so far
I have tried using generated functions and SimpleTraits.jl, but they both have the side effect of making julia think that there is a method of g
for all types.
What I would like to do is this
@generated function g(x)
if method_exists(f, Tuple{x})
return quote
y = f(x)
return modify(y)
end
else
# don't return anything and leave g without a method for typeof(x)
end
end
The reason I don’t want Julia to think there are methods available is because I want to be able to use method_exists
to print out a nice table of the functions that the users still need to implement to use the package.
The users of my package are usually non-CS engineers new to Julia, are not very experienced with object-oriented programming, and I’m trying to show them how powerful the language is in addition to introducing them to the package, so I’m trying to keep things as simple as possible.