Overloading a function specifically for symbolics

The type of a symbolic is Num:

julia> using Symbolics
julia> @variables x
julia> typeof(x)
Num

How can I write a function specifically for symbolics? Let’s say there is already a genericfun(x::Num, y::Num) defined in Base or some standard library package. How could I overload this function solely for symbolics?

1 Like

I’m not sure what you mean by symbolic variables. Do you mean you want the function to accept a Symbol? For example, you can multiply two numbers, and use multiply to concatenate two strings, but there is no method for Symbols. However we can define one by importing the function:

julia> :h * :ello
ERROR: MethodError: no method matching *(::Symbol, ::Symbol)

julia> import Base.*

julia> *(x::Symbol, y::Symbol) = Symbol(String(x) * String(y))        
* (generic function with 843 methods)

julia> :h * :ello
:hello

Or are you more thinking in the context of computer algebra systems (CAS)? For that you can use Symbolics.jl.

Can you describe in more detail what you’re trying to do?

If you’re talking about Num from Symbolics.jl, this would be considered type piracy, since neither the type Num nor the function genericfun are originally from your code. Type piracy is usually a bad idea and can lead to unintended side effects.

If you think it makes sense for genericfun to be defined for Num types, maybe that’s worth a PR to Symbolics.jl.

If not, depending on what you’re trying to accomplish, you might want to either use a different function name (the easier option) or create a wrapper type of your own around Num.

Sorry, my question wasn’t clear enough. I mean a symbolic, defined in the Symbolics package. I edited the question to reflect this.

If I were to do what I’m asking, I would indeed do it inside the Symbolics package and open a PR. For now it’s simply an academic question. I don’t understand how the package can specialise on symbolic values only, if they’re defined to be Num, which is a very general type.

So I’ve realised that I was confusing the type Num (actually defined in the Symbolics package) with the generic type Number. So in fact I can just specialise on Num.