Why can I not add methods to a function with a value?

I was trying to add a method to a function that accepts strings but not integers to convert integers to strings if necessary.
For instance, given f = reverse, I get 16 methods, none of which apply to numerical types.

Now, I want to add f(x::Integer) = reverse(string(x)). I would expect that this would add a new method for Integers that would for example map 123 to "321".

However, I get an error:
ERROR: cannot define function f; it already has a value

Even though there would be no conflict in the methods assigned to f, Julia doesn’t let me add this additional method to it because I originally defined it as equal to reverse.

I thought this might be a result of shallow copying; however, I tried g = deepcopy(reverse) and got the same results.

Is there any way to clone Julia functions and add methods to them (not extending existing functions)? Is the current behavior a bug, or intended?

You probably have assigned something to f already (maybe reverse?).

1 Like

Yes, I have assigned the 16 methods of reverse to the function f already, but I am confused why I cannot add more methods to it that do not conflict with its existing definition.

You need to do f(x) = reverse(x), not f = reverse, if you want to add additional methods to f (without affecting Base.reverse). That is, f needs to be a new generic function, not an alias for Base.reverse.

If you want to add new methods to Base.reverse itself, you need to do Base.reverse(...new args...) = ...new implementation..., since you’re not allowed to extend methods in other modules without explicitly qualifying them with the module name (or explicitly importing them).


Got it, thanks!