Manually Merge Functions

I have seen a lot of discussion related to this and the general consensus seems to be that it would be a mistake to automatically merge functions from different packages. However, is there a way to manually do this?

For example, say I define something like this:

function plot_predictions(model, xs)
    plot(xs, predict(model, xs))
end

Then say I am using a few different packages with different models

using Foo # defines ModelFoo and predict(::ModelFoo, xs)
using Bar # defines ModelBar and predict(::ModelBar, xs)

Unfortunately, the packages define different predict functions, meaning that when we try to run the plot_predictions function, we end up with an error saying we need to qualify predict (Foo.predict or Bar.predict).

Is there a way I can do something like predict = merge(Foo.predict, Bar.predict) where the method table of the new function is created by merging the method tables of the arguments?

2 Likes

You could write a new function that checks which of the predict functions supports the given argument types and then call that one. Something like the following:

function my_predict(model, xs)
    if applicable(Foo.predict, model, xs)
        Foo.predict(model, xs)
    elseif applicable(Bar.predict, model, xs)
        Bar.predict(model, xs)
    else
        error("No method found")
    end
end

I have written a package which defines a macro using_merge which does the merging you want when
loading packages.

My package is not yet registered but you can use it by

]add "https://github.com/jmichel7/UsingMerge.jl"
1 Like

And I have written a package that defines the same macro but for other types of arguments. If only there was a way to merge them.

1 Like

Can you give a link to your package, please?

Sorry, that was a bit of a joke.

1 Like