Using an `Int` as a `Num`

I am using Symbolics.jl. I have a function function f(a::Num,b::Num)::Num, but in using it I want to use, sometimes -

@variables x, z
y = f(1,x)

as well as

@variables x, z
y = f(z,x)

but I get an error because 1 is not a Num. How can I get around this? Can I convert 1 to a Num. I wish to keep the arguments in f as they are now.

I don’t know Symbolics, so please forgive me if this isn’t right, but I would guess that you can have the type of the argument be Union{Num, Const} or whatever type 1 is in the context of Symbolics.

You can remove ::Num from the signature of f.

1 Like

You can convert 1 to a Num like this:

julia> Num(1)
1

julia> typeof(ans)
Num

You are overconstraining your function arguments, and there is no need for the return-type declaration either. If you want to declare argument types for dispatch or clarity, you can declare your function as f(a::Number, b::Number), for example, since both Int and Num are subtypes of Number. But it is perfectly fine to leave out the argument types entirely.

(Such type declarations typically do nothing for performance in Julia, contrary to popular misconception.)

1 Like