I know that in Julia the multiple-dispatch makes it (almost?) obsolete the creation of structs with functions. But I was wondering if for my case it would be useful. Consider that I have a plotting package that receives a m::Marker
and draws it. Now, I wish that users of the package could implement their own markers, which would be drawn according to a function drawmarker(m::Marker)
. The thing is, for the set of markers I've implemented, I have the multiple-dispatch setup, i.e.
drawmarker(m::Circle)
drawmarker(m::Bar)
But since I wish a user can create his own marker, I was wondering if it would be better for the marker struct to have a drawmarker
as a method. Any thoughts? Should I just make the user pass a drawmarker
function as an argument?
To clarify, what is wrong with user-defined drawmarker(m::CustomMarker)
?
Nothing really wrong about. Mostly about design. I mean, I'd have something like:
plot(m::Marker)
which my package provides. Now, the plot
function calls drawmarker
inside of it. But requiring the user to write a drawmarker
function, it would also require that he passed his function to the plot
function, and I'd need to check whether or not he passed the function to run it instead of the already defined inside the package. What I mean, is, if the drawmarker
was a method from the marker, then I could keep the plot(m::Marker)
. Otherwise, I need something like:
function plot(m::Marker; drawfunction::Function = nothing)
if drawfunction === nothing
drawmarker(m)
else
drawfunction(m)
end
end
So, I'm not saying that it cannot be done. Just that It looks like an uglier solution than just defining the drawmarker
as a method of the marker. Hence, I was wondering if it was still advisable not to create the method for the marker.
I think, what Andrey meant is for the user to write something like
import Package: drawmarker
struct MyCustomMarker end
function drawmarker(m::MyCustomMarker)
# specify how to draw it
end
plot(m::MyCustomMarker)
Hmm, this would work out of the box? I thought since the function with dispatch for the custom marker is not in my package, it would not work. If it indeed works, then all my problems are resolved :)
The import Package: drawmarker
line is what makes it work
See here too: https://docs.julialang.org/en/v1/manual/modules/#using-and-import-with-specific-identifiers,-and-adding-methods
Yeah, this is such a beautiful thing about Julia’s multiple dispatch
Last updated: Dec 28 2024 at 04:38 UTC